Scanner 类中的 nextLine 方法不接受输入(Java)
这是我的代码:
for (int arrayIndex = 0; arrayIndex < 5; arrayIndex++)
{
PhoneBookEntry PhoneBook = new PhoneBookEntry();
System.out.println("Please enter a name");
tempName = keyboard.nextLine();
PhoneBook.setName(tempName);
System.out.println("Please enter a corresponding phone number");
tempNum = keyboard.nextInt();
PhoneBook.setPhoneNum(tempNum);
EntryList.add(PhoneBook);
}
显然第二次尝试时 nextLine 方法有问题。我该如何解决这个问题?我不允许为此使用除扫描仪之外的任何类。
谢谢
编辑:它给出的错误是一个例外:
Exception in thread "main" java.util.InputMismatchEx
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 PhoneBookApp.main(PhoneBookApp.java:39)
Here's my code:
for (int arrayIndex = 0; arrayIndex < 5; arrayIndex++)
{
PhoneBookEntry PhoneBook = new PhoneBookEntry();
System.out.println("Please enter a name");
tempName = keyboard.nextLine();
PhoneBook.setName(tempName);
System.out.println("Please enter a corresponding phone number");
tempNum = keyboard.nextInt();
PhoneBook.setPhoneNum(tempNum);
EntryList.add(PhoneBook);
}
Apparently there is a problem with the nextLine method on the second try. How could I fix this? I am not allowed to use any class other than scanner for this.
Thanks
EDIT: The error it gives is an exception:
Exception in thread "main" java.util.InputMismatchEx
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 PhoneBookApp.main(PhoneBookApp.java:39)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您应该使用
String
类型作为电话号码,而不是int
。它会给你一些与某些数字不匹配的异常。在这种情况下,使用String
会更合适。I think you should use a
String
type for the phone numbers rather than anint
. It would give you mismatch exceptions with certain numbers. In this instance using aString
would be more appropriate.这是在 Google 上搜索“nextLine”时的第一个结果
Here is the first result on Google when googling "nextLine"