1

I want to create a program that allows me to enter name, age, and year of birth for 5 different people. However, I get a problem where I cannot enter another name after I entered the first in my for loop. Here is my code:

public static void main(String[] args) {

    String[] names = new String[5];
    int[] s = new int[5];
    Scanner keyboard = new Scanner (System.in);

    for (int i = 0; i < 5; i++) {
        System.out.print("Name: ");
        names[i] = keyboard.nextLine();
        System.out.print("Age: ");
        s[i] = keyboard.nextInt();
        System.out.print("Year: ");
        s[i] = keyboard.nextInt();
    }
}

The program works fine when I run it, but it will not allow me to enter the other 4 names after I entered the first. Here is the output I am getting:

sample output

Behroz Henayat
  • 101
  • 2
  • 9
  • 3
    http://stackoverflow.com/questions/13102045/skipping-nextline-after-use-next-nextint-or-other-nextfoo-methods – Reimeus May 09 '15 at 20:41

2 Answers2

3

Please note:

String java.util.Scanner.next() - Returns:the next token
String java.util.Scanner.nextLine() - Returns:the line that was skipped

Change your code [do while initial lines] as below:

names[i] = keyboard.next();
Rajesh
  • 2,120
  • 1
  • 10
  • 14
2

Take a look- I've fixed your code- added "keyboard.nextLine();" at the end.

public static void main(String[] args) {


        String[] names = new String[5];
        int[] s = new int[5];
        Scanner keyboard = new Scanner (System.in);

        for (int i = 0; i < 5; i++) {

            System.out.print("Name: ");
            names[i] = keyboard.nextLine();
            System.out.print("Age: ");
            s[i] = keyboard.nextInt();
            System.out.print("Year: ");
            s[i] = keyboard.nextInt();
            keyboard.nextLine();
        }
    }

The reason you need to add it is that "nextInt()" will only read what you've entered and not the rest of the line. What's left of the line will be then read by "names[i] = keyboard.nextLine();" automatically.

By putting another "keyboard.nextLine()" at the end, I've skipped what left of the line and then "names[i] = keyboard.nextLine();" gets a new line to read input from.

Every beginner in Java encounters this problem sooner or later :)

Jacob.B
  • 677
  • 1
  • 8
  • 19