2015-04-04 120 views
0
中計數爲零

我自己開始學習大約4天的編程,並且iam一點點卡住了2d數組。我試着挑戰自己與任務,比如從二維數組列中獲取大部分零或至少算了算零,到目前爲止,我走到這一步Java 2d陣列在列

public class b { 

    public static void main(String[] args) { 
     int a[][] = new int [5][5]; 
     int i,j; 
     int s = 0; 

     for(i= 0;i<a.length; i++) 
      for(j = 0; j<a[i].length; j++){ 
       a[i][j] = (int)(Math.random()*10); 
      } 
     for(i=0;i<a.length;i++){ 
      for(j=0;j<a[i].length;j++) { 
       System.out.print(a[i][j] + "\t"); 
      } 
      System.out.println(); 
     } 

     for(j=0;j<a[0].length;j++) { 
      for(i=0;i<a.length;i++) { 
       if(a[i][j] >-1 || a[i][j]<1) { 
        s++; 
        System.out.println(s +"\t");    
        s = 0; 
       } 
      } 
     } 

    }  
} 

有人可以解釋我爲什麼結果總是1,爲什麼它計算列和行中的行?

+1

因爲你reassingning'S = 0;' – silentprogrammer 2015-04-04 10:51:24

+0

如果你剛開始學習編程,請進入正確縮進你的代碼的習慣 - 基本上,增加縮進當您打開{塊,減少它就在你用}關閉一個塊之前。它使其他人(和你)更容易閱讀你的代碼。 – 2015-04-04 10:54:28

+0

@singhakash沒有它,它計數1,2,3,4等 – ArtG 2015-04-04 10:55:41

回答

0

假設條件進入if(a[i][j] >-1 || a[i][j]<1)則增加S按1然後打印其給出1則其重新分配給s=0所以它賦予相同1每個time.So除去s=0並放置在印刷線環

結束後
public class b { 

public static void main(String[] args) { 
    int a[][] = new int [5][5]; 
    int i,j; 
    int s = 0; 

    for(i= 0;i<a.length; i++) 
     for(j = 0; j<a[i].length; j++){ 
      a[i][j] = (int)(Math.random()*10); 
     } 
    for(i=0;i<a.length;i++){ 
     for(j=0;j<a[i].length;j++) 

     System.out.print(a[i][j] + "\t"); 
     System.out.println(); 
    } 

    for(j=0;j<a[0].length;j++){ 
    for(i=0;i<a.length;i++) 
     if(a[i][j] >-1 && a[i][j]<1){ 
     s++; 

     } 
    System.out.println("Zero in column no. "+j+" is "+s +"\t"); 
    s=0; 
    } 

    } 
} 

Demo

+0

它如何找到最大計數爲零的列? – 2015-04-04 11:00:34

+0

@RohitJain OP不詢問爲什麼它只打印1? – silentprogrammer 2015-04-04 11:11:10

+0

@singhakash謝謝你的迴應,但是如果行不等於列,那麼我得到一個錯誤類似「java.lang.ArrayIndexOutOfBoundsException」我需要添加異常或什麼? – ArtG 2015-04-04 12:37:51

0

結果將是1,因爲你重新分配0s每次。但問題不僅在於此。

首先你的情況是使用錯誤的索引。在列順序遍歷時,應該使用a[j][i]而不是a[i][j]。其次:

if(a[j][i] >-1 || a[j][i]<1){ 

可簡單地寫爲:

if(a[j][i] == 0) { 

所以結構是外for循環將遍歷每個列號。並且對於每個列號,內部for循環將找到計數0。您必須在兩個循環之外維護一個max變量,以跟蹤當前的最大值。另外,您必須使用外部for循環內的另一個變量來存儲當前列的計數。

每當內部for循環結束時,檢查當前列數是否大於max。如果是,則重置max

int max = 0; 
for(j=0;j<a[0].length;j++){ 
    int currentColumnCount = 0; 
    for(i=0;i<a.length;i++) { 
     if(a[j][i] == 0) { 
      currentColumnCount++; 
     } 
    } 
    if (currentColumnCount > max) { 
     max = currentColumnCount; 
    } 
} 
+0

,但它沒有錯?整數只包含逗號後沒有數字的整數?在你的例子中,它統計了整個數組中的零,但是我怎樣才能算出每行的零呢? – ArtG 2015-04-04 11:26:35