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.