欢迎来到天天文库
浏览记录
ID:13011767
大小:33.00 KB
页数:4页
时间:2018-07-20
《java的输入语句总结》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、java的输入语句小结)1.使用Scanner使用时需要引入包importjava.util.Scanner;首先定义Scanner对象Scannersc=newScanner(System.in);如果要输入整数,则intn=sc.nextInt();String类型的,则Stringtemp=sc.next();比如:importjava.util.Scanner;publicclassTest{publicstaticvoidmain(String[]args){Scannerscanner=newScanner(
2、System.in);int[]days={31,28,31,30,31,30,31,31,30,31,30,31};intmonth=-1;while(true){try{System.out.print("请输入月份:");month=scanner.nextInt();if(month>=1&&month<=12){break;}System.out.println("**请输入正确的月份**");}catch(Exceptione){System.out.println("**格式错误!请输入数字**");sca
3、nner.next();}}System.out.println(month+"月份有:"+days[month-1]+"天");}}2.使用BufferedReader用前需要引入importjava.io.Reader;BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));Stringinput=br.readLine();比如: importjava.io.*; publicclassimporttext{ publicstati
4、cvoidmain(String[]args){ Stringst; intnum; floatfnum; try{ System.out.print("输入:"); BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in)); st=br.readLine(); System.out.print("输入一个数:"); num=Integer.parseInt(br.readLine()); System.out.print(
5、"输入一个浮点数:"); fnum=Float.parseFloat(br.readLine()); System.out.print("输出:"+st+'n'); System.out.print("输出:"+num+'n'); System.out.print("输出:"+fnum+'n'); }catch(IOExceptione){} } }packagecom.s2;importjava.io.*;publicclassInput{publicstaticvoidmain(String[]args
6、)throwsIOException{while(true){BufferedReaderbuf;Stringstr;buf=newBufferedReader(newInputStreamReader(System.in));System.out.println("Inputastring:");str=buf.readLine();System.out.println("String="+str);}}}=========================================================
7、=========================================应该注意的是:Java把从键盘输入的数据一律看作是字符串,因此若要从键盘输入并让系统认可是数值型数据,必须经过转换。比如:packagecom.s2;importjava.io.*;publicclassInput{publicstaticvoidmain(String[]args)throwsIOException{while(true){intnum;BufferedReaderbuf;Stringstr;buf=newBuffered
8、Reader(newInputStreamReader(System.in));System.out.println("Inputaninteger:");str=buf.readLine();num=Integer.parseInt(str);System.out.println("String="+str);Sy
此文档下载收益归作者所有