TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
Scanner是SDK1.5新增的一个类,可是使用该类创建一个对象.
Scanner reader=new Scanner(System.in);
然后reader对象调用下列方法(函数),读取用户在命令行输入的各种数据类型:
next.Byte(),nextDouble(),nextFloat,nextInt(),nextLine(),nextLong(),nextShot()
上述方法执行时都会造成堵塞,等待用户在命令行输入数据回车确认.例如,拥护在键盘输入12.34,hasNextFloat()的值是true,而hasNextInt()的值是false. NextLine()等待用户输入一个文本行并且回车,该方法得到一个String类型的数据。
下面是一个实例:
- import java.util.*;
- public class Example{
- public static void main(String args[]){
- System.out.println("请输入若干个数,每输入一个数用回车确认");
- System.out.println("最后输入一个非数字结束输入操作");
- Scanner reader=new Scanner(System.in);
- double sum=0;
- int m=0;
- while(reader.hasNextDouble()){
- double x=reader.nextDouble();
- m=m+1;
- sum=sum+x;
- }
- System.out.printf("%d个数的和为%f
- ",m,sum);
- System.out.printf("%d个数的平均值是%f
- ",m,sum/m);
- }
- }
- 运行结果:
- C:java>java Example
- 请输入若干个数,每输入一个数用回车确认
- 最后输入一个非数字结束输入操作
- 34.1
- 34
- 45
- d
- 3个数的和为113.100000
- 3个数的平均值是37.700000
复制代码
C:java>
另一个例子,读取并分析文本文件:hrinfo.txt,文本文件的内容如下:
老赵,28,feb-01,true
小竹,22,dec-03,false
阿波,21,dec-03,false
凯子,25,dec-03,true
程序:
- import java.util.Scanner;
- import java.io.File;
- import java.io.FileNotFoundException;
- public class readhuman {
- private static void readfile(String filename) {
- try {
- Scanner scanner = new Scanner(new File(filename));
- scanner.useDelimiter(System.getProperty("line.separator"));
- while (scanner.hasNext()) {
- parseline(scanner.next());
- }
- scanner.close();
- }catch (FileNotFoundException e) {
- System.out.println(e);
- }
- }
- private static void parseline(String line) {
- Scanner linescanner = new Scanner(line);
- linescanner.useDelimiter(",");
- //可以修改usedelimiter参数以读取不同分隔符分隔的内容
- String name = linescanner.next();
- int age = linescanner.nextInt();
- String idate = linescanner.next();
- boolean iscertified = linescanner.nextBoolean();
- System.out.println("姓名:"+name+" ,年龄:"+ age+" ,入司时间:"+ idate+" ,验证标记:"+iscertified );
- }
- public static void main(String[] args) {
- if (args.length != 1) {
- System.err.println("usage: java readhuman file location");
- System.exit(0);
- }
- readfile(args[0]);
- }
- }
- 运行结果:
- C:java>java readhuman hrinfo.txt
- 姓名:老赵 ,年龄:28 ,入司时间:feb-01 ,验证标记:true
- 姓名:小竹 ,年龄:22 ,入司时间:dec-03 ,验证标记:false
- 姓名:阿波 ,年龄:21 ,入司时间:dec-03 ,验证标记:false
- 姓名:凯子 ,年龄:25 ,入司时间:dec-03 ,验证标记:true
-
复制代码
|
|