控制台中输入字符(Java)
- 格式:docx
- 大小:24.69 KB
- 文档页数:2
java输入数据的方法Java是一种面向对象的编程语言,提供了丰富的输入数据的方法,本文将介绍几种常用的输入数据的方法。
一、使用Scanner类Scanner类是Java标准库提供的一个用于读取用户输入的类。
通过Scanner类,我们可以方便地从控制台或文件中读取不同类型的数据。
1. 从控制台读取数据要从控制台读取数据,可以使用以下代码:```javaimport java.util.Scanner;public class InputExample {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.print("请输入一个整数:");int num = scanner.nextInt();System.out.println("您输入的整数是:" + num);System.out.print("请输入一个字符串:");String str = scanner.nextLine();System.out.println("您输入的字符串是:" + str);scanner.close();}}```上述代码中,我们首先创建了一个Scanner对象,并传入System.in作为参数,表示从标准输入流中读取数据。
然后通过nextInt()方法读取一个整数,通过nextLine()方法读取一行字符串。
最后,记得调用scanner的close()方法关闭输入流。
2. 从文件读取数据要从文件中读取数据,可以使用以下代码:```javaimport java.io.File;import java.io.FileNotFoundException;import java.util.Scanner;public class FileInputExample {public static void main(String[] args) {try {File file = new File("input.txt");Scanner scanner = new Scanner(file);while (scanner.hasNextLine()) {String line = scanner.nextLine();System.out.println(line);}scanner.close();} catch (FileNotFoundException e) {System.out.println("文件不存在");}}}```上述代码中,我们首先创建了一个File对象,指定要读取的文件路径。
但是,在使用第三种输入方法的时候有一个需要注意的地方,就是nextLine()函数,在io包中有一个和他功能一样的函数我next()函数,他们的功能一样,但是在实现上有什么差别呢,请看下面代码:public static void main(String[]args){Scanner sc=new Scanner(System.in);System.out.println("请输入你的年龄:");int age=sc.nextInt();System.out.println("请输入你的姓名:");String name=sc.nextLine();System.out.println("请输入你的工资:");float salary=sc.nextFloat();System.out.println("你的信息如下:");System.out.println("姓名:"+name+"\n"+"年龄:"+age+"\n"+"工资:"+salary);}这段代码和上边第三种实现输入方法给出的例子代码区别在于,这段代码先执行nextInit()再执行nextLine(),而第三种方法的例子是先执行nextLine(),再执行nextInit(),当你在运行着两段代码的时候你会发现第三种方法的例子可以实现正常的输入,而这段代码却在输入年龄,敲击enter键后,跳过了输入姓名,直接到了输入工资这里,(可以自己运行代码看看)这是为什么呢?其实,在执行nextInit()函数之后,敲击了enter回车键,回车符会被nextLine()函数吸收,实际上是执行了nextLine()函数吸收了输入的回车符(并不是没有执行nextLine函数),前面讲到和nextLine()功能一样的函数next(),他们的区别就在于:next()函数不会接收回车符和tab,或者空格键等,所以在使用nextLine()函数的时候,要注意敲击的回车符有个被其吸收,导致程序出现BUG!!!最后小小的总结一下next()和nextLine()的区别:在java中,next()方法是不接收空格的,在接收到有效数据前,所有的空格或者tab键等输入被忽略,若有有效数据,则遇到这些键退出。
package com.五子棋.code;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;public class Code2 {String[][] s=new String[15][15];boolean flag=true;public void f4(){for(int i=0;i<s.length;i++){for(int j=0;j<s[i].length;j++){s[i][j]="╋";System.out.print(s[i][j]);}System.out.println();}}public boolean f1(int x,int y){if((x>=0&&x<15)&&(y>=0&&y<15)){if(s[x][y]=="☻"||s[x][y]=="○"){return false;}return true;}return false;}public void f2(int x,int y){boolean b=f1(x,y);if(b==true){f3(x,y);}else{System.out.println("输入格式不正确或重复,请重新输入");}}public void f3(int x,int y){for(int i=0;i<s.length;i++){for(int j=0;j<s[i].length;j++){if(i==x&&j==y){if(flag==true){s[x][y]="☻";flag=false;}else{s[x][y]="○";flag=true;}}System.out.print(s[i][j]);}System.out.println();}if(f5(x,y,"☻")==1){System.out.println("__________");System.out.println("黑子胜利");return;}else if(f5(x,y,"○")==1){System.out.println("白子胜利");return;}}public int f5(int x,int y,String f){int jact1=0,jact2=0;for(int i=0;i<s.length;i++){for(int j=0;j<s[i].length;j++){//判断横向五子while(s[x][y-jact1]==f&&y-jact1>=0||s[x][y+jact1]==f&&j-jact1<15) {jact1++;if(jact1==5){System.out.println("11111111111");return 1;}}//判断横向左右两边五子jact1=0;jact2=0;while((s[x][y-jact1]==f)&&(y-jact1>=0)){jact1++;while(s[x][y+jact2]==f&&(y+jact2<15)){jact2++;if(jact2==5){break;}}if(jact1+jact2==6){System.out.println("2222222222222222");return 1;}}jact1=0;jact2=0;//判断竖向五子while(s[x-jact1][y]==f&&x-jact1>=0||s[x+jact1][y]==f&&j+jact1<15){jact1++;if(jact1==5){System.out.println("3333333333333");return 1;}}//判断竖向上下五子jact1=0;jact2=0;while((s[x-jact1][y]==f)&&(x-jact1>=0)){jact1++;while(s[x+jact2][y]==f&&(x+jact2<15)){jact2++;if(jact2==5){break;}}if(jact1+jact2==6){System.out.println("4444444444444444444");return 1;}}//判断左上方五子jact1=0;jact2=0;while(s[x-jact1][y-jact1]==f&&(y-jact1>=0)&&(x-jact1>=0)){jact1++;if(jact1==5){System.out.println("55555555555555555555");return 1;}}//判断左边斜向上下五子jact1=0;jact2=0;while(s[x-jact1][y-jact1]==f&&y-jact1>=0&&y-jact1>=0){jact1++;while(s[x+jact2][y+jact2]==f&&y+jact2<15&&x-jact2<15){jact2++;if(jact2==5){break;}}if(jact1+jact2==6){System.out.println("666666666666666");return 1;}}//判断右上方五子jact1=0;jact2=0;while(s[x+jact1][y+jact1]==f&&(y-jact1<15)&&(x-jact1<15)){jact1++;if(jact1==5){System.out.println("77777777777777");return 1;}}//判断右边斜向上下五子jact1=0;jact2=0;while(s[x+jact1][y-jact1]==f&&y-jact1>=0&&x+jact1<15){jact1++;while(s[x-jact2][y+jact2]==f&&y+jact2<15&&x-jact2>=0){jact2++;if(jact2==5){break;}}if(jact1+jact2==6){System.out.println("888888888888888888888");return 1;}}}}return 0;}public static void main(String [] args){Code2 co=new Code2();co.f4();System.out.println("是否开始游戏【yes】开始");BufferedReader br=new BufferedReader(new InputStreamReader(System.in));String str=null;try {while((str=br.readLine())!=null){if("yes".equals(str)){System.out.println("黑子先手-请输入坐标(0~15的数字,不含15)");String t1,t2;while((t1=br.readLine())!=null){System.out.println("+++++++++++++++");t2=br.readLine();int a1=Integer.parseInt(t1);int a2=Integer.parseInt(t2);co.f2(a1,a2);System.out.println("----------");}}else{System.out.println("****************");}}} catch (IOException e) {e.printStackTrace();}}}。
Java读取输⼊字符和字符串1. 使⽤Scanner读取字符和字符串3/**4 * Created by SheepCore on 2020-2-265*/7public class Main {8public static void main(String[] args) {9 Scanner scan = new Scanner(System.in); //声明⼀个Scanner对象,初始输⼊流为控制台10 String name = scan.nextLine(); //读取键盘输⼊字符串(包括空格、Tab,不包括最后的Enter)11 String id = scan.nextLine();12int age;13float height;14double weight;15 age = scan.nextInt(); //读取下⼀个int(光标停在本⾏的空格之前)16 height = scan.nextFloat(); //读取下⼀个float17 weight = scan.nextDouble(); //读取下⼀个double1819 System.out.println("name: " + name + "\nid: " + id);20 System.out.println("age: " + age + " height: " + height + " weight: " + weight);21 }22 }sheepcore1100110022 178.3 68.5name: sheepcoreid: 11001100age: 22 height: 178.3 weight: 68.52. 使⽤System.in.read()读取单个字符如果只要读取⼀个字符可以通过read()⽅法实现。
计算机科学系本科学年论文题 目java 应用程序——控制台输入法学生姓名 闫 洛专业名称 软件工程指导教师 田絮资2013年1月15日班 级 2010级软件工程2班学生学号 201096064076Java应用程序—控制台输入法闫洛(宝鸡文理学院计算机科学系,陕西宝鸡 721016)Java applications - console input methodYan Luo(Department of Computer Science, Baoji Univ.Arts&Sci., Baoji 721016 , Shaanxi, China)摘要Java已经从一种平台无关的编程语言演变成一种与厂商及平台无关的健壮的服务器端技术,促使IT业界深入发掘以Web为核心的应用程序的巨大潜力。
在java的语言里包括了大量的类与方法,由它们来主导java语言的应用。
本文主要研究java应用程序的控制台输入法,主要叙述Scanner类,包括它的介绍、用法、发展以及示例分析。
本文主要包括四个部分:(1)java应用程序,主要描述java简介以及java 应用程序的开发过程,以引出下文。
(2)从控制台输入数据,该部分为本文的核心,主要讲述Scanner类及一些使用方法。
(3)控制台输入数据相关的类和方法,该部分主要讲了和控制台输入相关的重要的类和方法。
(4)总结,对全文进行总结。
关键字:java,控制台输入,Scanner。
AbstractJava is from a platform-independent programming language evolved into a server-side technology has nothing to do with the manufacturers and platform robust, great potential to promote IT industry to explore the application to Web as the core. In the Java language includes classes and methods of application, by them to dominate the Java language. Console input method based on Java application, mainly describesthe Scanner class, including the introduction, development, usage and example analysis.This paper mainly includes four parts: ( 1 ) the Java application, describes the development process of Java and Java applications, to introduce below. ( 2 ) the input data from the console, this part is the core of this dissertation, mainly about the Scanner class and use method. ( 3 ) the class and method for console input data, this part is mainly about the classes and methods related to important and console input. ( 4 ) conclusion, summarizes the full text.Key words: java,Console input,Scanner.目录摘要 (1)1java应用程序 (4)1.1java简介 (4)1.2 java应用程序的开发过程 (4)1.2.1 编写源文件 (4)1.2.2 编译 (5)1.2.3 运行 (5)1.2.4 使用开发工具Eclipse (5)2从控制台输入数据 (7)2.1 从控制台输入的方法 (7)2.1.1 引言 (7)2.1.2 JDK 1.4 及以下版本读取的方法 (7)2.1.3 JDK 5.0 读取的方法 (8)2.1.4 JDK 6.0 读取的方法 (9)2.2 scanner类 (11)2.2.1 scanner类的介绍 (11)2.2.2 示例解释 (11)2.3 控制台输入数据的几种常用方法 (12)2.3.1 使用标准输入串对象System.in (12)2.3.2 使用Scanner取得一个字符串或一组数字 (12)2.3.3 使用BufferedReader取得含空格的输入 (13)3控制台输入数据相关的类和方法 (14)3.1 Scanner类 (14)3.2 System类 (15)3.3 in方法 (15)3.4 nextInt (15)4 总结 (16)1java应用程序1.1java简介Java是由Sun Microsystems公司于1995年5月推出的Java面向对象程序设计语言(以下简称Java语言)和Java平台的总称。
11:byte[ ] data=new byte[1];12:BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile)); 13:BufferedOutputStream bos = new BufferedOutputStream(newFileOutputStream(dstFile));14:while(bis.read(data) != -1) bos.write(data);15:bos.flush();16:System.out.println("文件复制成功!");17:bis.close();18:bos.close();19:}catch(IOException e){20: e.printStackTrace();21:}22:}23:}可见利用标准输入流进行控制台输入的方式非常麻烦:如果从键盘获取的是字符串,需要采用B u ffered Read e r类来进行处理;如果获取的是其他类型数据,需要手工进行转换;在读取的过程中还必须捕获IO E xcep t io n。
不过这是JDK1.4及更早版本中从控制台读取数据唯一办法。
7.8.2 使用Scanner类的方式从JDK5.0开始,ja va.u t il包中增加了S c a n ner类,它是一个可以使用正则表达式来解析基本类型和字符串的简单文本扫描器。
S can ne r类从字面上讲是“扫描”的意思,它把给定的字符串解析成Jav a的各种基本数据类型,用于分解字符串的默认的分隔符是空格,也可以定制。
其构造方法如表7-15。
表7-15S cann er类的构造方法方法描述Scanner(File source)Scanner(File source, String charsetName)构造一个新的Scanner,其值是从指定文件扫描获得。
java控制台输⼊输出⼀、⽐较传统的输⼊⽅法⽤输⼊流,得到字符串后要另⾏判断、转换案例import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;public class MainRun {public static void main(String[] args) {try {BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));System.out.println("请输⼊⼀个整数:");String str1 = bufferedReader.readLine();Integer int1 = Integer.valueOf(str1);System.out.println("输⼊的整数是:" + int1);System.out.println("请输⼊⼀个浮点数:");String str2 = bufferedReader.readLine();Double double1 = Double.valueOf(str2);System.out.println("输⼊的浮点数是:" + double1);} catch (IOException e) {e.printStackTrace();}}}请输⼊⼀个整数:234输⼊的整数是:234请输⼊⼀个浮点数:23输⼊的浮点数是:23.0⼆、JDK5以后有了Scanner处理控制台输⼊格式1: Scanner sc = new Scanner(new BufferedInputStream(System.in));格式2: Scanner sc = new Scanner(System.in);在有多⾏数据输⼊的情况下,⼀般这样处理:while(sc.hasNextInt()){...} 或者while(sc.hasNext()){}读⼊⼀个字符串: String str = sc.next();读⼊⼀整⾏数据: String lineString=sc.nextLine();读⼊⼀个布尔值:boolean boolenaNumber = sc.nextBoolean();读⼊⼀个字节型数据:byte byteNumbe = sc.nextByte();读⼊⼀个短整型数据:short shortNumber=sc.nextShort();读⼊⼀个整数:int intNumber = sc.nextInt();读⼊⼀个长整型数据:long longNumber=sc.nextLong();读⼊⼀个单精度浮点数:float floatNumber=sc.nextFloat();读⼊⼀个双精度浮点数:double doubleNumber=sc.nextDouble();对于计算代码运⾏时间:long startTime = System.nanoTime();// … the code being measured …long estimatedTime = System.nanoTime() - startTime;输⼊案例:输⼊数据有多组,每组占2⾏,第⼀⾏为⼀个整数N,指⽰第⼆⾏包含N个实数Scanner sc = new Scanner(System.in);while(sc.hasNext()){int n = sc.nextInt();for(int i=0;i<n;i++){double a=sc.nextDouble();...}三、输出:输出内容:System.out.print("");输出内容并换⾏:System.out.println("");格式化输出: System.out.format(String format, Object ... args);等价于 System.out.printf((String format, Object ... args);各种格式化样式说明:格式化输出案例:// System.out.printf(format, args);format为指定的输出格式,args参数System.out.printf("%+8.3f\n", 3.14); // "+"表⽰后⾯输出的数字会有正负号,正的+,负的-// ;8.3f表⽰输出浮点数,宽度为8,⼩数点保持3位有效System.out.printf("%+-8.3f\n", 3.14);// "-"表⽰靠左对齐System.out.printf("%08.3f\n", 3.14);// "0"8位宽度中⾃动补0System.out.printf("%(8.3f\n", -3.14);// "("如果是负数,⾃动加上( )System.out.printf("%,f\n", 123456.78); // ","⾦钱表⽰⽅法,每三位有⼀个逗号System.out.printf("%x\n", 0x2a3b); // 输出16进制数System.out.printf("%#x\n", 0x2a3b);// 输出带0x标识的16进制数System.out.printf("⽼板:您名字%s,年龄:%3d岁,⼯资:%,-7.2f\n", "ajioy", 21,36000.00);System.out.printf("⽼板:您名字%1$s,年龄:%2$#x岁\n", "ajioy", 38); // "n{1}quot;表⽰⽤第n个参数输出结果:+3.140+3.1400003.140(3.140)123,456.7800002a3b0x2a3b⽼板:您名字ajioy,年龄: 21岁,⼯资:36,000.00⽼板:您名字ajioy,年龄:0x26岁五、规格化输出SimpleDateFormat:SimpleSimpleDateFormat myFmt = new SimpleDateFormat("yyyy年MM⽉dd⽇ HH时mm分ss秒 E ");System.out.println(myFmt.format(new Date()));输出结果:2016年09⽉08⽇ 17时34分01秒星期四DecimalFormat:DecimalFormat 是 NumberFormat 的⼀个具体⼦类,⽤于格式化⼗进制数字。
java的输入语句小结java的输入语句小结Java中做输入的方式:通过控制台输入数据,需要使用Scanner对象来操作,那么java输入语句到底有哪些呢?下面跟yjbys店铺一起来看看吧!1.使用Scanner使用时需要引入包import java.util.Scanner;首先定义Scanner对象Scanner sc = new Scanner(System.in);如果要输入整数,则 int n = sc.nextInt();String类型的,则String temp = sc.next();比如:import java.util.Scanner;public class Test {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};int month = -1;while(true) {try {System.out.print("请输入月份:");month = scanner.nextInt();if(month >= 1 && month <= 12) {break;}System.out.println("** 请输入正确的.月份 **");} catch (Exception e) {System.out.println("** 格式错误!请输入数字 **");scanner.next();}}System.out.println(month + " 月份有:" + days[month - 1] + " 天");}}2.使用BufferedReader用前需要引入 import java.io.Reader;BufferedReader br = new BufferedReader( new InputStreamReader(System.in) );String input = br.readLine();比如:====================================== ========================================= ===================import java.io.*;public class importtext {public static void main(String[] args) {String st;int num;float fnum;try{System.out.print("输入:");BufferedReader br=new BufferedReader(new InputStreamReader(System.in));st = br.readLine();System.out.print("输入一个数:");num = Integer.parseInt(br.readLine());System.out.print("输入一个浮点数:");fnum = Float.parseFloat(br.readLine());System.out.print("输出:"+st+'n');System.out.print("输出:"+num+'n');System.out.print("输出:"+fnum+'n');}catch(IOException e){}}}====================================== ========================================= ===================package com.s2;import java.io.*;public class Input{public static void main(String[] args)throws IOException{while(true){BufferedReader buf;String str;buf =new BufferedReader(new InputStreamReader(System.in));System.out.println("Input a string:");str=buf.readLine();System.out.println("String="+str);}}}====================================== ========================================= ===================应该注意的是:Java把从键盘输入的数据一律看作是字符串,因此若要从键盘输入并让系统认可是数值型数据,必须经过转换。