2016-05-12 25 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 +"."); 
} 
相關問題