Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Scanner class reading strings

I got the following code:

int nnames; String names[];  System.out.print("How many names are you going to save: "); Scanner in = new Scanner(System.in); nnames = in.nextInt(); names = new String[nnames];  for (int i = 0; i < names.length; i++){   System.out.print("Type a name: ");   names[i] = in.nextLine(); } 

And the output for that code is the following:

How many names are you going to save:3  Type a name: Type a name: John Doe Type a name: John Lennon 

Notice how it skipped the first name entry?? It skipped it and went straight for the second name entry. I have tried looking what causes this but I don't seem to be able to nail it. I hope someone can help me. Thanks

like image 406
marcoamorales Avatar asked Sep 23 '09 14:09

marcoamorales


People also ask

Can a Scanner scan a string Java?

A simple text scanner which can parse primitive types and strings using regular expressions. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

Which method of the Scanner class is used to input a string?

Answer. Answer: As the name is a string, the Scanner object uses the next () method. For class input, it uses nextInt () while for percentage it uses nextFloat ().


1 Answers

The reason for the error is that the nextInt only pulls the integer, not the newline. If you add a in.nextLine() before your for loop, it will eat the empty new line and allow you to enter 3 names.

int nnames; String names[];  System.out.print("How many names are you going to save: "); Scanner in = new Scanner(System.in); nnames = in.nextInt();  names = new String[nnames]; in.nextLine(); for (int i = 0; i < names.length; i++){         System.out.print("Type a name: ");         names[i] = in.nextLine(); } 

or just read the line and parse the value as an Integer.

int nnames; String names[];  System.out.print("How many names are you going to save: "); Scanner in = new Scanner(System.in); nnames = Integer.parseInt(in.nextLine().trim());  names = new String[nnames]; for (int i = 0; i < names.length; i++){         System.out.print("Type a name: ");         names[i] = in.nextLine(); } 
like image 139
Joshua Avatar answered Sep 21 '22 15:09

Joshua