我试图获取用户输入并使用正则表达式对其进行验证。但是,当我运行程序时,它似乎没有等待接收任何其他用户输入。相反,我得到了
线程中的异常" main" java.util.NoSuchElementException`
对正在发生的事情的任何帮助都会很棒!
这是我的代码:
//Retrieve name
System.out.println("What name would you like to search for? (Enter first name only without spaces)");
Scanner input = new Scanner(System.in);
while (!input.hasNext("[A-Za-z]+")) {
System.out.println("Invalid entry. Please enter first name only.");
input.next();
}
String name = input.next();
System.out.println("You gave me as input the name:" + name);
}
答案 0 :(得分:1)
工作正常。尝试将其作为完全正常工作的类(将其保存为 myInput.java
,然后使用javac myInput.java
编译,然后使用>运行 em> java myInput
):
import java.io.*;
import java.util.Scanner;
class myInput {
public static void main(String[] args) {
//Retrieve name
System.out.println("What name would you like to search for? (Enter first name only without spaces)");
Scanner input = new Scanner(System.in);
while (!input.hasNext("[A-Za-z]+")) {
System.out.println("Invalid entry. Please enter first name only.");
input.next();
}
String name = input.next();
System.out.println("You gave me as input the name:" + name);
}
}
OUTPUT(我首先给出无效输入(test1),然后正确打印有效(测试)):
test1
Invalid entry. Please enter first name only.
test
You gave me as input the name:test