初学者java构造函数+循环+表ArrayIndexOutOfBounds

时间:2014-04-07 10:33:31

标签: java constructor indexing indexoutofboundsexception

初学者在这里找不到我的问题的答案。首先,这是代码。

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

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

我想要做的是创建3个“工人”对象(让我们假设用户正在选择“n”值),而只有两组数据(名称,姓氏和年龄)。如果“n”值大于names.length(),我想用构造函数“public Worker(){}”创建新的worker。

我该怎么做?我已经尝试了几个想法但是所有想法都给了我ArrayIndexOutOfBoundsException。

2 个答案:

答案 0 :(得分:1)

  

如果&#34; n&#34; value大于names.length我想要新的   使用构造函数&#34; public Worker(){}&#34;。

创建的worker

这样的东西?

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

答案 1 :(得分:-1)

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

这将检查姓名,姓氏或年龄是否具有最多索引,然后使用它来初始化您的Worker数组。