【发布时间】:2018-05-15 06:46:38
【问题描述】:
我有两个版本的 Java 代码可以获取用户输入,直到用户键入“q” 版本 1:
public class Test {
public static void main(String[] args) {
String input = "";
while (!input.equals("q")) {
Scanner scanner = new Scanner(System.in);
System.out.print("Input: ");
input = scanner.nextLine();
System.out.println("Input was: " + input);
}
}
}
版本 2:
public class Test {
public static void main(String[] args) {
String input = "";
while (!input.equals("q")) {
try(Scanner scanner = new Scanner(System.in)){
System.out.print("Input: ");
input = scanner.nextLine();
System.out.println("Input was: " + input);
}
}
}
}
第 1 版按预期工作,但第 2 版无法按预期工作。 也就是第一次读取用户输入后,会产生错误
Input: 12
Input was: 12Exception in thread "main"
Input: java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at RealEstateCompany.main(RealEstateCompany.java:115)
我的猜测是因为版本 2 使用 try with resource 所以它在使用后关闭扫描仪并导致错误?
提前感谢您的帮助!
[更新] 版本 3:
public class Test {
public static void main(String[] args) {
String input = "";
try(Scanner scanner = new Scanner(System.in)){
while (!input.equals("q")) {
System.out.print("Input: ");
input = scanner.nextLine();
System.out.println("Input was: " + input);
}
}
}
}
版本 3 有效。但是,为什么版本3可以,而版本2不行呢?
【问题讨论】:
-
try-with自动关闭底层Scanner,即自动关闭底层流,即System.in。之后,您将无法再获得任何用户输入。 -
您是否尝试将 try(Scanner scanner = new Scanner(System.in)) 排除在 while 循环之外?
-
@RajuSharma 谢谢你的建议。是的,它解决了我的问题,但为什么这能解决问题?
-
版本 3 有效,因为当您进入
while循环时,您仍然在try块内。仅当您离开try时,资源才会关闭,这是您的第二个示例在一次迭代后发生的情况。 -
@QBrute 谢谢你的回答!我对 Java 还很陌生,所以你能告诉我更多细节吗?
标签: java try-catch try-with-resources