2014-02-08 50 views
-1

我想輸出列大小和二維數組的行大小。我的程序編譯但打印出來:爲什麼數組1的長度大於預期?

Welcome to DrJava. Working directory is C:\Users\mulk\Downloads 
> run Lab4 
Print out the rowsize: 4.0 
Print out the columnsize: 4.0 
> 

不應該行大小爲3.0?我從零開始計數。

/* 
* Purpose: Prints the row and column averages 
*/ 
class Lab4 
{ 
    public static void main(String[] args) 
    { 

    int [][] scores = {{ 20, 18, 23, 20, 16 }, 
         { 30, 20, 18, 21, 20 }, 
         { 16, 19, 16, 53, 24 }, 
         { 25, 24, 22, 24, 25 }}; 
    outputArray(scores); 
    } 

    public static void outputArray(int[][] array) 
    { 
    double rowsize = 0.0; 
    double columnsize= 0.0; 
    for(double i=0.0;i <= array.length;i++) 
    { 
     rowsize = array.length; 
    } 
    System.out.println("Print out the rowsize: " +rowsize); 

    for (double j = 0; j <=array[0].length; j++) 
    { 
     columnsize = array.length; 
    } 
    System.out.println("Print out the columnsize: " +columnsize); 
    } 
} 
+0

尺寸從1開始,索引從0開始。如果你有一個行,它可能會被收錄爲0行(取決於語言),但我們仍然說「大小」爲1. – crockeea

+1

正如Eric所說的,但是......您可以只是'System.out.println(「rows:」+ scores.length);'和' System.out.println(「cols:」+ scores [0] .length);' – MrSimpleMind

回答

0

二維數組只是一個數組數組。因此,爲了找出有多少行,我們將執行arrayName.length,然後找出每列中有多少項,我們將不得不前往第一行(數組),並通過arrayName [0]找出該長度。長度。

所以你可以看到你正在使用的代碼找出有多少行有兩次。它應該是這個樣子:

double rowsize = 0.0; 
    double columnsize= 0.0; 

    rowsize = array.length; 
    System.out.println("Print out the rowsize: " +rowsize); 

    if(rowsize >= 1){ 
     columnsize = array[0].length; 
    } 
    System.out.println("Print out the columnsize: " +columnsize); 

我希望這解決您的問題:)

相關問題