Java 简明教程

Java Scanner Class

Introduction

Java Scanner 类是一个简单的文本扫描器,它可以使用正则表达式解析基本类型和字符串。以下是有关 Scanner 的要点 -

The Java Scanner class is a simple text scanner which can parse primitive types and strings using regular expressions.Following are the important points about Scanner −

  1. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

  2. A scanning operation may block waiting for input.

  3. A Scanner is not safe for multithreaded use without external synchronization.

Class declaration

以下是 java.util.Scanner 类的声明 -

Following is the declaration for java.util.Scanner class −

public final class Scanner
   extends Object
   implements Iterator<String>

Class constructors

Class methods

Methods inherited

此类从以下类中继承方法:

This class inherits methods from the following classes −

  1. java.util.Object

Reading a Line from Console using Scanner Class Example

下面的示例展示了如何使用 Java Scanner nextLine() 从控制台读取一行,并使用 close() 方法关闭扫描器。我们使用给定的字符串创建一个扫描器对象。然后我们使用 nextLine() 方法打印字符串,然后使用 close() 方法关闭扫描器。

The following example shows the usage of Java Scanner nextLine() to read a line from Console and close() method to close the scanner. We’ve created a scanner object using a given string. Then we printed the string using nextLine() method and then scanner is closed using close() method.

package com.tutorialspoint;

import java.util.Scanner;

public class ScannerDemo {
   public static void main(String[] args) {

      String s = "Hello World! 3 + 3.0 = 6";

      // create a new scanner with the specified String Object
      Scanner scanner = new Scanner(s);

      // print the next line of the string
      System.out.println(scanner.nextLine());

      // close the scanner
      System.out.println("Closing Scanner...");
      scanner.close();
      System.out.println("Scanner Closed.");
   }
}

Output

让我们编译并运行上述程序,这将生成以下结果 −

Let us compile and run the above program, this will produce the following result −

Hello World! 3 + 3.0 = 6
Closing Scanner...
Scanner Closed.