在下面的代码片段中,在我输入coach的值并按enter之后,scanner抛出了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();
抛出异常。谢谢大家!
1条答案
按热度按时间igsr9ssn1#
当您调用
sc.nextLine()
来读取coach时,它会遇到上一次nextLong()
调用留下的换行符。因此,它读取一个空行(将换行符解释为输入行),并继续执行,而不允许您输入 coach name。我的建议是始终使用
nextLine()
并转换为想要的Class
,如下所示:字符串
请看:
你也可以这样做:
型