Johnny
Johnny

Reputation: 1437

nextLine method in Scanner class not accepting input (Java)

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)

Upvotes: 0

Views: 1112

Answers (2)

Mob
Mob

Reputation: 11098

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();

Upvotes: 2

K2xL
K2xL

Reputation: 10270

Here is the first result on Google when googling "nextLine"

Upvotes: 0

Related Questions