Scanner 类中的 nextLine 方法不接受输入(Java)

发布于 2024-12-12 06:40:46 字数 920 浏览 0 评论 0原文

这是我的代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小清晰的声音 2024-12-19 06:40:46

我认为您应该使用 String 类型作为电话号码,而不是 int。它会给你一些与某些数字不匹配的异常。在这种情况下,使用 String 会更合适。

System.out.println("Please enter a corresponding phone number");
String tempNum = keyboard.nextLine();

I think you should use a String type for the phone numbers rather than an int. It would give you mismatch exceptions with certain numbers. In this instance using a String would be more appropriate.

System.out.println("Please enter a corresponding phone number");
String tempNum = keyboard.nextLine();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文