Scanner在nextInt上抛出NoSuchElementException

逻辑工作正常,但是当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) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at view.ClientFacade.main(ClientFacade.java:18) 

下面是我的代码,为什么这个Scanner会产生这个错误? 还有其他方法可以从键盘上读取吗?

 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 viariable实例化。

 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 ; 一旦你关闭System.in唯一的方法来恢复它是重新启动你的程序。

每个close() Javadoc,

如果此扫描程序尚未关闭,那么如果其底层可读也实现了Closeable接口,那么将调用可读的close方法

您关闭了关闭基础流的Scanner 。 不要用标准的细节来做到这一点。