import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class Lab1 {
public static void main(String args[])
throws InterruptedException {
System.out.println("Please enter your first name.");
String name;
Scanner sc = new Scanner(System.in);
name = sc.nextLine();
System.out.println(name);
Thread.sleep(1200);
}
}
由于扫描仪仍处于打开状态,因此用户可以在暂停期间输入内容。它不会使程序崩溃,但我仍然希望能够关闭扫描仪并稍后在代码中重新打开它。
答案 0 :(得分:1)
从Java 7开始,Scanner
实现了AutoCloseable
,因此您可以使用try-with-resources自动关闭它:
String name;
try (Scanner in = new Scanner(System.in)) {
name = in.nextLine();
}
System.out.println(name);