如何在Java中以二维数组分别获取数字?

时间:2016-05-12 19:53:23

标签: java arrays loops for-loop multidimensional-array

这就是问题:

  

(g)鉴于以下声明:

int [][]hours = new int[3][2];
     

存储周三(周五和周六)工作时间(假设没有工作的部分工作时间)为三名员工。

     

将一段Java代码写入:

     
      
  1. 计算并打印所有员工的总工作小时数

  2.   
  3. 每位员工的平均工作时间。

  4.         

    假设数组已填充数据。

我完全迷失了这就是我所能想到的:

int [][] hours = new int[3][2];

for (int i = 0; i++; i < hours[0].length){
    int totalHours;
    for(int j = 0 j++; j < hours[1].length){
        totalHours = totalHours + hours[i][j];
        System.out.println("The total hours employee " + j + "worked is " + totalHours + ".");
    }
    totalHours = 0;
}

3 个答案:

答案 0 :(得分:1)

首先,您的for循环不正确。 for循环应该像这样写

for(init variable; condition; increment)

所以你的for循环应该是这样的

for (int i = 0; i < hours[0].length; i++)

至于你的条件,你用嵌套for循环遍历2d数组的方式是外循环将沿着行向下移动。因此,你的第一个条件应该是这样的

i < hours.length

然后你的内部循环基于当前行,或外部循环中的i值。所以你的内循环条件应该是

j < hours[i].length

答案 1 :(得分:0)

考虑到这是一个家庭作业问题,我会尝试引导您走上正确的轨道。

对于初学者,您没有正确访问二维阵列。

以下是如何访问二维数组中每个元素的示例。

int [][] hours = new int[3][2];

for(int i = 0; i < hours.length; i++) //correct way to initialize a for loop
{
    //do foo to the outer array;

    for(int j = 0; j < hours[i].length; j++)
    {
        //do foo to the inner arrays
    }
}

答案 2 :(得分:0)

问题在于for循环。以下是更正后的代码:

int[][] hours = new int[3][2];

for(int i=0; i<hours.length; i++){
    int totalHours = 0;
    for(int j =0; j< hours[i].length; j++){
        totalHours = totalHours + hours[i][j];
    }
    System.out.println("The total hours employee " + i + " worked is " + totalHours +".");
}
相关问题