Java 等待输入
    
    
            Siddharth Swami
    2023年10月12日
    
    Java
    Java Input
    
用户输入可以指用户希望编译器处理的任何信息或数据。我们可能会遇到希望程序暂停编译并等待用户输入某个值的情况。
对于这种情况,我们可以使用 nextLine() 函数。
在本教程中,我们将学习如何使用 nextLine() 方法让 Java 等待用户输入。
nextLine() 函数位于 Java 的 java.util.Scanner 类中。此函数用于移过当前行并返回一些输入。
因此,通过使用此方法,编译器等待用户输入有效字符串并继续编译程序。此方法仅适用于字符串数据类型。
例如,
// Java program to illustrate the
// nextLine() method of Scanner class in Java
import java.util.Scanner;
public class Scanner_Class {
  public static void main(String[] args) {
    // create a new scanner
    // with the specified String Object
    Scanner scanner = new Scanner(System.in);
    String s = scanner.nextLine();
    // print the next line
    System.out.println("The line entered by the user: " + s);
    scanner.close();
  }
}
输入:
Hello World.
输出:
The line entered by the user: Hello World.
无需等待检查输入的可用性,因为 Scanner.nextLine() 将自动阻塞,直到有一行可用。
下面的代码解释了这一点。
import java.util.Scanner;
public class Scanner_Test {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    try {
      while (true) {
        System.out.println("Please input a line");
        long then = System.currentTimeMillis();
        String line = scanner.nextLine();
        long now = System.currentTimeMillis();
        System.out.printf("Waited %.3fs for user input%n", (now - then) / 1000d);
        System.out.printf("User input was: %s%n", line);
      }
    } catch (IllegalStateException | NoSuchElementException e) {
      // System.in has been closed
      System.out.println("System.in was closed; exiting");
    }
  }
}
输出:
Please input a line
Hello World.
Waited 1.892s for user input
User input was: Hello World.
Please input a line
^D
System.in was closed; exiting
在上面的例子中,我们使用 currentTimeMillis() 函数计算并显示了编译器等待输入的时间。
这个函数可能会返回两个异常。关闭 Scanner 时会引发 IllegalStateException,当找不到行时会引发 NoSuchElementException。
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe