1

I have a code here that creates an array and puts in people's names into it. However, the first array does not get recorded.

Scanner newscan = new Scanner(System.in);

    System.out.println("How many people in the group?");
    int groupnum = newscan.nextInt();

    String[] people = new String[groupnum];

    System.out.println("Put in the names of the people in the group");
    String name;

    int i = 0;
    do{
        System.out.println("Input Name");
        name = newscan.nextLine();
        people[i] = name;
        i++;
    }while(i<groupnum);

The console shows results like this:

How many people in the group?
5
Put in the names of the people in the group
Input Name
Input Name
John
Input Name
Bob
Input Name
Denis
Input Name
Andrew

I have tried using the debugger on IntelliJ, and it shows that whatever value I put in the first array, gets ignored and is set as a "" null value.

I have no idea to approach this problem. It would be very helpful if you can tell me what part of my code is causing this problem and how to fix it.

  • "" is not the same as null. This is due to you not consuming the newline in the `nextInt()` – Sami Kuhmonen Jun 07 '17 at 13:11
  • Possible duplicate of [Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo) – Sami Kuhmonen Jun 07 '17 at 13:11

4 Answers4

0

modify your code to this:

int groupnum = newscan.nextInt();
newscan.nextLine();
String[] people = new String[groupnum];

and remember that newscan.nextInt(); is not consumming the newline character, that is the reason why the code is not working and why you get:

Input Name 
Input Name

twice in a row

ΦXocę 웃 Пepeúpa ツ
  • 43,054
  • 16
  • 58
  • 83
0

After reading nextInt() method, new line is going as input. To avoid that use scanner class skip method.

Lakshman Miani
  • 324
  • 1
  • 5
  • 18
0

Check the Scanner.nextLine() javadoc. It's return line separator from the nextInt() input. You can just use it before your cycle

int i = 0;
newscan.nextLine();
do{
    System.out.println("Input Name");
    name = newscan.nextLine();
    people[i] = name;
    i++;
}while(i<groupnum);
0

Simply add this line

newscan.nextLine();

below this line

int groupnum = newscan.nextInt();
Manihtraa
  • 748
  • 3
  • 9
  • 22