Java 扫描仪在nextInt上抛出NoTouchElementException
但是,当while循环结束并重新开始时,当它再次使用此行->option=kb.nextInt();,从键盘读取我的下一个选项时,逻辑工作正常。这给了我一个例外,更准确地说是下面这个例外:Java 扫描仪在nextInt上抛出NoTouchElementException,java,Java,但是,当while循环结束并重新开始时,当它再次使用此行->option=kb.nextInt();,从键盘读取我的下一个选项时,逻辑工作正常。这给了我一个例外,更准确地说是下面这个例外: Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source)
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at view.ClientFacade.main(ClientFacade.java:18)
下面是我的代码,为什么这个扫描器会产生这个错误?还有其他方法可以从键盘读取数据吗
public class ClientFacade {
public static Scanner kb = new Scanner(System.in);
public static void main(String[] args) {
boolean exit = false;
int option = 0;
RegistrationController rc = new RegistrationController();
while(exit == false){
System.out.println("Menu:");
System.out.println("1 - Sign up on service.");
option = kb.nextInt(); //ERROR ON THIS LINE WHEN IT EXECUTES ON THE SECOND LOOP
switch(option){
case 0:{
exit = true;
break;
}
case 1:{
rc.userSignUp();
break;
}
default:{
System.out.println("Invalid option.");
break;
}
}
}
}
}
下面的方法位于另一个类文件RegistrationController.java上,因此它由上面的rc变量实例化
public void userSignUp(){
User usr = new User();
RegistrationController rc = new RegistrationController();
String regex = "$(\\w)+(\\,)(\\w)+(\\,)(\\d){2,3}(\\,)[F,M](\\,)(\\w)+(@)(\\w)+(.)(\\w)+((.)(\\w)+)(,)(\\w)+^";
Scanner sc = new Scanner(System.in);
System.out.println("Input a single line separated by COMMA,"
+ " the software will validade your entry.\n"
+ "1 - Your First Name, 2 - Your Second Name,"
+ " 3 - Your Age, 4 - Your Gender \n(F or M in UPPER CASE)"
+ " 5 - Your Email, 6 - Your Password:\n");
String s = sc.nextLine();
s = s.trim();
System.out.println("trimmed"); //DEBUG
String [] k = s.split(",");
char[] c = k[3].toCharArray();
if (Pattern.matches(regex, s)){
usr.setAdmLevel(0);
usr.setName(k[0]+" "+k[1]);
usr.setAge(Integer.parseInt(k[2]));
usr.setGender(c[0]);
usr.setEmail(k[4]);
usr.setPassword(k[5]);
if (rc.registerUser(usr) != 0){
System.out.println("Your are signed up! Your ID: "+usr.getId());
}else {
System.out.println("A problem ocurred, not registered.");
}
}else{
System.out.println("Wrong input pattern, try again.");
}
sc.close();
}
您关闭了关闭底层流的
扫描仪
。不要使用标准的输入和输出来执行此操作。当您调用sc.close()
时,它将关闭您的底层流,即System.in
;一旦您关闭系统。在
中,恢复该系统的唯一方法是重新启动程序
根据Javadoc
如果此扫描仪尚未关闭,则如果其底层readable也实现了Closeable接口,则将调用readable的close方法
您已运行到
流的末尾,但没有更多匹配的令牌…请尝试添加kb.nextLine()
afteroption=kb.nextInt()代码>非常感谢!它只是工作,是的,正如你说的,我正在关闭方法内部的sc,我认为id将关闭系统。在它内部,但它关闭所有程序输入流,明白了吗!:)非常感谢你!它只是工作,是的,正如你说的,我正在关闭方法内部的sc,我认为id将关闭系统。在它内部,但它关闭所有程序输入流,明白了吗!:)非常感谢你!它只是工作,是的,正如你说的,我正在关闭方法内部的sc,我认为id将关闭系统。在它内部,但它关闭所有程序输入流,明白了吗!:)