逻辑工作正常,但是,当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)
下面是我的代码,为什么此扫描程序会生成此错误?还有其他从键盘读取的方法吗?
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,取回它的唯一方法就是重新启动程序。
sc.close()
System.in
根据close()Javadoc,
close()
如果此扫描器尚未关闭,则其底层可读文件也实现了Closeable接口,则将调用该可读文件的close方法