Question

Beginner here, couldn't find the answer for my question. First, here's the code.

public class Worker{

    String name = "default";
    String surname = "default";
    int age = 0;

    public Worker(){ }

    public Worker(String inName, String inSurname, int inAge){
        name = inName;
        surname = inSurname;
        age = inAge;
    }

    public Worker(Worker worker){
        name = worker.name;
        surname = worker.surname;
        age = worker.age;
    }
}   

And:

public class Company{   

    public static void main(String[] args){

        int n = 2;
        Worker[] workers = new Worker[n];
        String[] names = {"John", "Kate"};
        String[] surnames = {"Doe", "McDonald"};
        int[] ages = {25, 31};

        for(int i=0; i<n; i++){         
            workers[i] = new Worker(names[i], surnames[i], ages[i]);
        }       
            for(Worker p: workers){
            System.out.printf("%s, %s, %d \n",p.name,p.surname,p.age);
        }
    }
}

What I want to do is to create 3 'Worker' objects (let's assume that "n" value is being choosen by user) while only having two sets of data (names, surnames and ages). In case that "n" value is greater than names.length() I want new worker to be created with constructor "public Worker(){}".

How do I do that? I've tried several ideas but all of them give me ArrayIndexOutOfBoundsException.

Était-ce utile?

La solution

In case that "n" value is greater than names.length I want new worker to be created with constructor "public Worker(){}".

Something like this?

for(int i=0; i<names.length; i++){         
    workers[i] = new Worker(names[i], surnames[i], ages[i]);
}
if (names.length < n) {
    for(int i = names.length; i<n; i++){
        workers[i] = new Worker();
    }
}

Autres conseils

String[] names    = {"John", "Kate", "one_name_to_much"};
String[] surnames = {"Doe", "McDonald"};
int[]    ages     = {25, 31};

Worker[] workers  = new Worker[Math.max(Math.max(names.length, surnames.length), ages.length)];

That will check if names, surnames or ages has the most indices and then use this to initialize your Worker array.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top