Scanner 类 useDelimiter("")用法

来源:互联网 发布:网易博客软件 编辑:程序博客网 时间:2024/05/17 04:12
Scanner类从字面上讲是“扫描”的意思,它把给定的字符串解析成Java的各种基本数据类型primitive types,用于分解字符串的默认的分隔符是空格,当然也可以定制。

例如:Scanner sc = new Scanner(System.in);其构造函数参数是待解析的输入源,可以是File对象、Stream对象,或是一个String,然后还有java.lang.Readable对象。

定制分隔符的方法是sc. useDelimiterj(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 0