如何强制Scanner.next()输出一个值?
问题描述:
我目前正在研究一个Java程序,该程序会在命令行上运行基本的配置文件编辑器。 我有1个问题...有些条目必须是有效的输出。 我尝试使用如何强制Scanner.next()输出一个值?
while(!scanner.hasNext()){
System.err.println("Invalid Value");
}
String str = scanner.next();
在我看来这应该工作,因为每次scanner.hasNext();被称为程序应暂停,直到在控制台中输入内容。 但是,当我运行程序(输入无效值)它只是保持循环循环。 我做错了什么或者这只是一个错误? 感谢您的帮助!
答
为了完整这里的目的是一个快速的解决方案,采用while (true)
-approach:
public static void main(String[] args) {
String input = null;
try (Scanner scanner = new Scanner(System.in)) {
while (true) {
System.out.println("Please enter SOME INFORMATION:");
if (scanner.hasNextLine()) {
input = scanner.nextLine();
if (inputIsSane(input)) break;
System.out.println("Your input is malformed. Please try again.");
}
}
}
System.out.println("Got valid input. Input was: " + input);
// continue with the rest of your program here
}
private static boolean inputIsSane(String input) {
// replace with your actual validation routine
return input.equals("let me pass");
}
你是说你得到“无效值”无限次被淹,因为它是在while循环? – Gendarme
如果'scanner.hasNext()'返回false,则表示您已到达流的末尾并多次调用它将无济于事。 –
@Gendarme基本上是的 – RoiEX