Hey guys! I'm writing this really long code for practice. Got really rusty with Java so I gotta get brain working again. Anyway, the first part of the code asks the user for the number of employees; the for loop then keeps asking the user to input employee names depending on the value of user input. The error I'm getting is that I haven't intialized arrayEmp. How do I make it so that the size of arrayEmp is from the user's input. Thanks guys! Every time I come to this site I just keep on learning!

public class Driver {


    public static void main(String[] args) {
        String[] arrayEmp;
        String empName;
        double numSales;
        double numCom; 
        Scanner s = new Scanner (System.in);
        System.out.print("Input number of employees: ");
        int numEmp = s.nextInt();


        for(int i = 0; i < numEmp; i++){
            System.out.print("Enter employee name: ");
            empName = s.next();
            arrayEmp[i] = empName; 
        }

    }

Array is a fixed size collection, so you have to declear it and cannot change the number of elements in it. Consider using ArrayList instead, it is a collection that can dinamically be allocated, you just add more items in it, look Here

arrayEmp = new String[numEmp];

as in...

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.print("Input number of employees: ");
        int numEmp = s.nextInt();
        String[] arrayEmp = new String[numEmp];
        for(int i = 0; i < numEmp; i++){
            System.out.print("Enter employee name: ");
            String empName = s.next();
            arrayEmp[i] = empName;
        }
    }

Slavi, Understandably you might wanna go for an arraylist. However in this case it isn't necessarily needed. Check JeffGrigg's reply for something that works using the setup laguardian is using.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.