A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 天火传说 中级黑马   /  2015-6-3 17:31  /  344 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

Java 5添加了java.util.Scanner类,这是一个用于扫描输入文本的新的实用程序。它是以前的StringTokenizer和Matcher类之间的某种结合。由于任何数据都必须通过同一模式的捕获组检索或通过使用一个索引来检索文本的各个部分。于是可以结合使用正则表达式和从输入流中检索特定类型数据项的方法。这样,除了能使用正则表达式之外,Scanner类还可以任意地对字符串和基本类型(如int和double)的数据进行分析。借助于Scanner,可以针对任何要处理的文本内容编写自定义的语法分析器。
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\n",m,sum);
System.out.printf("%d个数的平均值是%f\n",m,sum/m);
}
}
运行结果:
C:\java>java     Example请输入若干个数,每输入一个数用回车确认最后输入一个非数字结束输入操作34.13445d3个数的和为113.1000003个数的平均值是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
Scanner类从字面上讲是“扫描”的意思,它把给定的字符串解析成Java的各种基本数据类型primitive types,用于分解字符串的默认的分隔符是空格,当然也可以定制。
例如:Scanner sc = new Scanner(System.in);其构造函数参数是待解析的输入源,可以是File对象、Stream对象,或是一个String,然后还有java.lang.Readable对象。

定制分隔符的方法是sc. useDelimiter(Pattern),然后使用while循环和sc.next()来依次取出Scanner解析后的元素,还可以特定取sc.nextInt()/ nextLong()/ nextShort()/ nextDouble()等等。
最后,不管输入源是不是Stream,都请执行sc.close()方法,关闭Scanner,它同时会关闭其输入源(the source implements the Closeable interface)。
import java.io.*;
import java.util.*;
public class ScanFar {

    public static void main(String[] args) throws IOException {

        Scanner sc =

                new Scanner(new BufferedReader(new FileReader("words.txt")));

      //  sc.useDelimiter("分隔符"); 默认是空格

        while (sc.hasNext()) {

            System.out.println(sc.next());



        }

        sc.close();

    }

}

如果words.txt文件中的内容是:“So she went into the garden...”

那么结果如下,整个字符串按空格来分为了多个String对象

So

she

went

into

the

garden...



如果sc.useDelimiter("t"),那么结果按字母t来分解,如下:

So she wen

  in

o

he  garden...


发现被定义为分隔符的字母t被消除了,不作为结果的一部分
以前常常遇到要从字符串中取出某些部分,有了Scanner类,比Split()方便灵活多了。
注:sc.next()是从结果集中连续取值,如果要从一串字符中取出间插在中间的数字,那么使用sc.nextInt(),但是如果结果集中的下一个元素不是int类型的话就会抛出异常,要达到这一目的,在循环中添加if条件判断即可,如下:

While(sc.hasNext()){

if(sc.hasNextInt()){ // sc.hasNextShort()/hasNextDouble/…等各种基本数据类型

//做事件…

}

else{

next();//直接跳过

}

}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马