如何在阵列中一起添加索引?

时间:2017-04-20 03:00:56

标签: java

我正在进行一项任务,我不知道如何将索引添加到一起以获得可以显示的总和。请注意,我只是一名高中生,因此我的代码比您可能创建的任何代码都更加低效且效率低,但任何帮助都会受到赞赏。这就是我现在所生成的索引超出范围的例外:

System.out.println("Please enter the amount of workers you have");
        Scanner userInput = new Scanner (System.in);
        int workerAmount = userInput.nextInt();
        int payroll[][]= new int [workerAmount][6];
         for(int a = 0; a < payroll.length; a++){
          for(int b = 0; b < payroll[a].length; b++)
           {

            System.out.println("How many hours did this worker work?");
            Scanner use = new Scanner (System.in);
            int user = use.nextInt();
            payroll[a][b] = user;
        }
    }
    for(int i = 0; i < payroll.length; i++){
        for(int a = 0; a < payroll[i].length; a++){
            System.out.println(payroll[i][a]);
            int sum = (payroll[i + a][a]); 
        }
    }

1 个答案:

答案 0 :(得分:0)

总结所有值,试试这个:

int sum = 0;
for(int i = 0; i < payroll.length; i++){
    for(int a = 0; a < payroll[i].length; a++){
       sum += payroll[i][a];
    }
}

System.out.println("the sum is: " + sum);

上面的代码简单地遍历所有数组数组,并将每个元素的值添加到sum变量上,然后将其打印到控制台。