Java中Scanner的用法及其基本方法

1.Scanner的用法

(1)Scanner读数据;

1) Scanner类可以从控制台或文件读数据;

2)默认情况下,Scanner类用空白字符作为分割标记;

从键盘读入时用System.in创建一个Scanner,

Scanner input=new Scanner(System.in);

从文件读取时用文件创建一个Scanner,

Scanner input=new Scanner(new File(fileName));

(2)扫描基本数据类型的值;

如果Token是基本数据类型的值,可使用 nextByte(), nextShort(), nextInt(), nextLong(),nextFloat(), nextDouble(), 或 nextBoolean() 方法来获取它.

String s = "1 2 3 4";
Scanner scanner = new Scanner(s);
 
int sum = 0;
while (scanner.hasNext())
      sum += scanner.nextInt();
System.out.println("Sum is " + sum);

Scanner.close();

(3)Scanner可以指定一个单词作为分割符;

String s = "Welcome to Java! Java is fun! Java is cool!";
Scanner scanner = new Scanner(s);
scanner.useDelimiter("Java");
    
while (scanner.hasNext())
      System.out.println(scanner.next());

Scanner.close();

结果为:

Welcome to
!
 is fun!
 is cool!

(4)从WEB上读数据;

可以从文件中读数据,也可以从WEB服务器上读数据。

URL:统一资源定位器, WEB文件的唯一地址

URL url = new URL("www.google.com/index.html");

创建URL对象以后,使用URL类的openStream()方法获得输入流,使用这个输入流产生Scanner对象,如下

Scanner reader = new Scanner(url.openStream(),”utf-8”);

通过reader顺序读,获得资源中的文本数据。

2.Scanner基本方法

构造方法:

Scanner(File file);

Scanner(InputStream inputStream);

Scanner(Path path);

Scanner(String fromString);

Scanner(File file,String charsetName);

Scanner(InputStream inputStream, String charsetName);

Scanner(Path path, String charsetName);

 

主要方法:

hasNext(): boolean

next(): String

nextByte(): byte

nextShort(): short

nextInt(): int

nextLong(): long

nextFloat(): float

nextDouble(): double

useDelimiter(pattern: String): Scanner

close(): void

猜你喜欢

转载自blog.csdn.net/qq_40513088/article/details/88371861
今日推荐