似乎您在循环内调用 Scanner(System.in) ,尝试将其放在顶部或任何循环之前。这就是为什么测试有效而工作无效的原因。
Is this table a simple table? Please check document to confirm, If YES please Enter Y If NO please Enter N
y
Is this table a simple table? Please check document to confirm, If YES please Enter Y If NO please Enter N
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1585)
at ScannerIssue.main(ScannerIssue.java:11)
..
while(true){
System.out.print("Is this table a simple table? Please check document to confirm, If YES please Enter Y If NO please Enter N \n");
Scanner fileS = new Scanner(System.in);
String input = fileS.nextLine();
input = input.trim();
input = input.toLowerCase();
// tableCount ++;
fileS.close();
}
上面的代码导致错误 Move the Scanner fileS = new Scanner(System.in); 到方法或类范围的开头。
你可以使用这样的东西:
Scanner fileS = new Scanner(System.in); //moved out of the loop
while (true) {
System.out
.print("Is this table a simple table? Please check document to confirm, If YES please Enter Y If NO please Enter N \n");
String input = fileS.nextLine();
input = input.trim();
input = input.toLowerCase();
// tableCount ++;
if ("n".equalsIgnoreCase(input)) {
break;
}
}
fileS.close(); //moved out of the loop
System.out.println("Good bye!");
}
结果将是:
Is this table a simple table? Please check document to confirm, If YES please Enter Y If NO please Enter N
Y
Is this table a simple table? Please check document to confirm, If YES please Enter Y If NO please Enter N
A
Is this table a simple table? Please check document to confirm, If YES please Enter Y If NO please Enter N
N
Good bye!