gpt4 book ai didi

java - 扫描器在 nextInt 上抛出 NoSuchElementException

转载 作者:行者123 更新时间:2023-12-02 11:17:37 24 4
gpt4 key购买 nike

逻辑工作正常,但是当 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 变量实例化的。

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,

If this scanner has not yet been closed then if its underlying readable also implements the Closeable interface then the readable's close method will be invoked

关于java - 扫描器在 nextInt 上抛出 NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25175249/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com