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
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.
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 ().
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With