1

I'm trying to write a program which given the input for groupNum, the for loop will fill the array with the names that are entered in each position of the array (the number of positions is set by groupNum as well.

The Code:

import java.util.Scanner;
public class Groups {
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        String name;
        int groupNum;
        System.out.print("Enter number in group: ");
        groupNum = in.nextInt();
        String[] names = new String[groupNum];
        for(int i = 0; i < names.length; i++){
            System.out.print("Enter Name: ");
            name = in.nextLine();
            names[i] = name;
        }
        System.out.println(names[0]);
    }
}

The problems I'm having:

When 1 is entered for number of people in group, I get prompted to "Enter Name" then the program ends without letting me enter a name to be stored in the array.

When 2 is entered for the number of people in the group, I get prompted twice "Enter Name Enter Name: " it asks this twice as types, lets me enter a number, then the program ends.

In both cases it never prints the contents of the first position of the array from the last line outside the for loop.

I've had this problem several times when writing code in java, I'm new to java, what am I doing wrong to cause this error all the time?

C.StG
  • 69
  • 7
  • 1
    Well it's been marked as a duplicate, but I disagree because you didn't know what the problem was. A simple fix to your code is to change the input in the for loop to (name = in.next();) instead of (name = in.nextLine();) –  Feb 14 '18 at 23:16

0 Answers0