pdon pdon - 1 year ago 93
Java Question

Getting accurate int and String input

I am having trouble reading in strings from the user after reading in an int. Essentially I have to get an int from the user and then several strings. I can successfully get the user's int. However, when I begin asking for strings (author, subject, etc...), my scanner "skips" over the first string input.

For example, my output looks like this:
Enter your choice:
Enter author:
Enter subject:

As you can see, the user is never able to enter the author, and my scanner stores null into the author string.

Here is the code that produces the above output:

String author;
String subject;
int choice;
Scanner input = new Scanner(System.in);

System.out.println("Enter choice:");
choice = input.nextInt();
System.out.println("Enter author:");
author = input.nextLine();
System.out.println("Enter subject:");
subject = input.nextLine();

Any help would be greatly appreciated. Thank you!
-Preston Donovan

Answer Source

The problem is that when you use readLine it reads from the last read token to the end of the current line containing that token. It does not automatically move to the next line and then read the entire line.

Either use readLine consistently and parse the strings to integers where appropriate, or add an extra call to readLine:

System.out.println("Enter choice:");
choice = input.nextInt();

input.nextLine(); // Discard the rest of the line.

System.out.println("Enter author:");
author = input.nextLine();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download