views:

1256

answers:

2

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

+2  A: 
Joshua
+1  A: 

It's because the in.nextInt() doesn't change line. So you first "enter" (after you press 3 ) cause the endOfLine read by your in.nextLine() in your loop.

Here a small change that you can do:

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());
    names = new String[nnames];

    for (int i = 0; i < names.length; i++){
            System.out.print("Type a name: ");
            names[i] = in.nextLine();
    }
Nettogrof