2016-05-12 68 views
-2

这是一个问题:如何在Java中的二维数组中分别获取数字?

(克)给定如下声明:

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

存储周末(星期五&周六)工作时间(假设没有部分工作时间)对每个三雇员。

编写的Java代码片断:

  1. 计算并打印由全体员工通过每个员工的工作

  2. 平均工作小时数的整体总小时数。

假设数组已填充数据。

而且我完全失去了,这是所有我能猜出:

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

在您的第一个'for'循环中,它应该是'i Logan

+2

“这是一个问题:...”。我无法在帖子中找到任何问题。这在语法上也是不正确的。 – ChiefTwoPencils

回答

0

考虑到这是一个家庭作业的问题,我会尽力把你引导到正确的轨道。

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

下面是如何访问2d数组中的每个元素的示例。

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 
    } 
} 
+0

这是一个过去的考试问题。从学习的几个小时我就死了一半,这就是为什么它比我所希望的更加混乱。我今天有一个测试,我的演讲喜欢对测试含糊不清,所以我试图确保我知道如何去做每一个过去的考试问题。 感谢您的帮助,虽然:) –

1

所有for循环首先是不正确的。 for循环应该这样写

for(init variable; condition; increment) 

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

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

至于你的条件,你的方式穿越嵌套二维数组的for循环,是外循环将沿着行。因此,你的首要条件应该是这样的

i < hours.length 

那么你的内循环是基于当前行,否则我在你的外环的价值上。所以你的内循环条件应该是

j < hours[i].length 
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 +"."); 
}