提问人:Programmer AHN 提问时间:7/27/2023 更新时间:7/27/2023 访问量:52
sc.nextLine() 抛出 InputMismatchException,而 sc.next() 不会
sc.nextLine() throws InputMismatchException while sc.next() doesn't
问:
在下面的代码片段中,在我输入 coach 的值并按 Enter 键后,扫描仪正在抛出。但是,如果我使用 ,则不会抛出此类异常。InputMismatchException
coach=sc.next();
void accept() {
System.out.println("Enter name , mobile number and coach for the customer and also the amount of ticket.");
name=sc.nextLine();
mobno= sc.nextLong();
coach=sc.nextLine();
amt=sc.nextInt();
}
我预计在这两种情况下都不会出现异常,但是我不明白为什么仅针对 .
谢谢大家!sc.nextLine();
答:
2赞
Diego Borba
7/27/2023
#1
当您调用读取 Coach 时,它会遇到上一次调用留下的换行符。因此,它会读取一个空行(将换行符解释为输入行)并继续操作,而不允许您输入教练名称。sc.nextLine()
nextLong()
我的建议是始终使用并转换为想要的,如下所示:nextLine()
Class
void accept() {
System.out.println("Enter name , mobile number and coach for the customer and also the amount of ticket.");
name = sc.nextLine();
// Cast long value
mobno = Long.valueOf(sc.nextLine());
coach = sc.nextLine();
// Cast int value
amt = Integer.parseInt(sc.nextLine());
}
看看这个:
但你也可以这样做:
void accept() {
System.out.println("Enter name, mobile number, coach for the customer, and also the amount of ticket.");
name = sc.nextLine();
mobno = sc.nextLong();
// Consume the remaining newline character in the input buffer
sc.nextLine();
coach = sc.nextLine();
amt = sc.nextInt();
}
评论
0赞
Programmer AHN
7/27/2023
谢谢,它有效!
1赞
Diego Borba
7/27/2023
@ProgrammerAHN 不客气!
评论