2012-04-05 54 views
1

這是一個myprogramminglab問題。 我給了一個數組(a2d),我需要確定每行和每列的元素數量是否與每隔一行和每列相同。如果是,那麼我將布爾isSquare設置爲true。Java 2d數組,測試方塊

我已經拿出了下面的代碼,但它不喜歡它,它沒有給我任何關於如何改進它的建議。

for(int row = 0; row < a2d.length; row++){ 
for(int col = 0; col < a2d[row].length; col++) 
    if(a2d.length == a2d[row].length) 
     isSquare = true; 
    else 
     isSquare = false; 
} 

我是測試這個錯誤的方式還是有更好的方法?

感謝

回答

5

沒有必要爲2個循環,你應該能夠做這樣的事(我不會放棄的代碼,因爲它的作業)

1. Save the length of the array (a2d.length) 
2. Loop over all the rows 
3. Check to see if the given row has the same length 
4. if Not return false 
5. if you reach the end of the loop return true 
+0

看到我的代碼上面的實現。 – 2012-04-05 01:55:45

+2

感謝大家的幫助。我更喜歡這種回答。 – 2012-04-05 02:49:12

0
if(a2d.length == a2d[row].length) 
    isSquare = true; 
else 
    isSquare = false; 

如果最後一個元素穿過這將返回true始終。試試這個:

isSquare = true; 
for(int row = 0; row < a2d.length; row++){ 
for(int col = 0; col < a2d[row].length; col++) 
    if(a2d.length != a2d[row].length) 
     isSquare = false; 
} 
+1

沒有必要遍歷每一列它不會改變if語句 – twain249 2012-04-05 02:00:14

+0

我認爲這是主要問題,它並沒有傳遞所有元素時返回true。 – 2012-04-05 02:36:15

1
for (int i = 0, l = a2d.length; i < l; i++) { 
    if (a2d[i].length != l) { 
    return false; 
    } 
} 
return true; 

您只需確保第二維數組的所有長度與第一維數組的長度相同。

+0

這是正確的答案(twain249接受的答案也是如此)。我無法理解誰和爲什麼投這一票。 – Male 2017-07-29 19:08:00