[英]How do I close scanner during sleep method?
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);
}
}
Because the scanner is still open, users can type during the pause. 由于扫描仪仍处于打开状态,因此用户可以在暂停期间输入内容。 It doesn't crash the program, but I still want to be able to close the scanner and be able to reopen it later on in the code. 它不会使程序崩溃,但我仍然希望能够关闭扫描仪并稍后在代码中重新打开它。
As of Java 7, Scanner
implements AutoCloseable
, so you can use try-with-resources to close it automatically: 从Java 7开始, Scanner
实现了AutoCloseable
,因此您可以使用try-with-resources自动关闭它:
String name;
try (Scanner in = new Scanner(System.in)) {
name = in.nextLine();
}
System.out.println(name);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.