简体   繁体   中英

The Program is not recording the first array, set as a null — Java

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.

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

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

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);

Simply add this line

newscan.nextLine();

below this line

int groupnum = newscan.nextInt();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM