1

I have a problem with a scanner. I want the program to read strings and an integer. I have two different situations. For example, my program asks the user to enter the year of birth, full name, and city.

Scanner input = new Scanner(System.in);
int year;
String name;
String city;
String state;

System.out.print("Please enter the year of birth to add: ");
year = input.nextInt();

System.out.print("Please enter full name to add: ");
name = input.nextLine();

System.out.print("Please enter a city to add: ");
city = input.nextLine();

System.out.println("Please enter the state to add: );
state = input.next();

Output:

Please enter the year of birth to add: 22
Please enter full name to add: Please enter a city to add: Denver

The first situation is the program skips the question and ask the next question. Without nextLine, it will receive an exception.

For the second situation, supposed if the city has two or more spaces(ex. San Francisco, New York City...), will the nextLine help or not? It seems similar with the first situation. I know nextLine will read a string with spaces, but it still cause a problem otherwise. I could not solve this issue.

Cactus
  • 25,576
  • 9
  • 60
  • 130
  • Put your variable defs right where you use them: `int year = input.nextInt()`. Don't stockpile them at the top. – mk. Mar 12 '15 at 01:27
  • @deafprogrammer24 I have a solution to your program. see if it works for you. – lacraig2 Mar 12 '15 at 01:31

1 Answers1

2

Try:

input.nextLine();   //this is totally useless and just eats up the rest of the line

after nextInt() and before nextLine(). It works.

Problem: In your code it does exactly what you tell it to. It takes in the integer and then continues on to the nextLine(). This is the same line. The nextInt() doesn't automatically go onto the next line. As such you can use nextLine() to eat up the end line.

Solution: sc.nextInt() eats up the integer, but not the new line. If you take the next line (same as nextInt()) it will go on to the real information on the next line and not skip a question.

Output:

Please enter the year of birth to add: 199
Please enter full name to add: 1234
Please enter a city to add: 1235123
Please enter the state to add: 1234123

Hope this helps.

lacraig2
  • 635
  • 4
  • 18
  • I am not sure to follow up what you suggest. I mean, why are all results in integer type? Does it mean I have to use nextInt() every time I scan? – deafprogrammer24 Mar 12 '15 at 03:20