2016-04-15 7 views
1

多次元配列でゼロを含むCOLUMNSの量を計算する方法。 0を含む行の数を計算できましたが、列の量を計算する方法を理解できません。助けてください。多次元配列で0を含むCOLUMNSの量を計算する方法

public class Main { 
    public static void main (String[] args) { 
     int i; 
     int j; 
     int count = 0; 
     int [][] arr = {{3, 0, 0, 6}, {4, 0, 1, 1}}; 
     for (i = 0; i < arr.length; i++) { 
      System.out.println(); 
      for (j = 0; j < arr[i].length; j++){ 
       System.out.print(arr[i][j] + ", "); 
      } 
     } 
     System.out.println(); 
     //----------------------------------------------------------- 
     for (i = 0; i<arr.length; i++) { 
      for (j = 0; j<arr[i].length; j++) { 
       if (arr[i][j] == 0) { 
        count++; 
        break; 
       } 
      } 
     } 
     System.out.println("the amount of rows containing zeros = " + count); 
    } 
} 
+3

ただ、 'ブレークを削除;'内部からこのコードは行の代わりに列の数を決定します。 – Titus

+0

ブレークを削除しただけで、列が2倍/ 3倍/などになるのを防ぐことができますか? 'arr [0] [0] == 0'と' arr [1] [0] == 0'の場合、countは2になります。 –

+0

@JonathanGawrychこれらの値のうち最大値を使用する必要があります – ritesht93

答えて

1

sqaure行列のために同じ結果を得るためのもう一つの簡単な方法は:

import java.util.*; 
import java.lang.*; 
import java.io.*; 

/* Name of the class has to be "Main" only if the class is public. */ 
class Ideone 
{ 
    public static void main (String[] args) throws java.lang.Exception 
    { 
     int i; 
     int j; 
     int count = 0; 
     int [][] arr = {{3, 0, 0, 6}, {4, 0, 1, 0}}; 

     for (i = 0; i < arr.length; i++) 
     { 
      System.out.println(); 
      for (j = 0; j < arr[i].length; j++) 
      { 
       System.out.print(arr[i][j] + ", ");} } 
       System.out.println(); 
      //-------------------------------------------------------------------- 

      for (i = 0; i<arr.length; i++) 
       for (j = 0; j<arr[i].length; j++) 
        if (arr[i][j] == 0) 
        { 
         count++; 
         break; 
        } 
      System.out.println("the amount of rows containing zeros = " + count); 

      //-------------------------------------------------------------------- 
      count=0; 

      for (i = 0; i<arr[0].length; i++) 
       for (j = 0; j<arr.length; j++) 
        if (arr[j][i] == 0) 
        { 
         count++; 
         break; 
        } 
      System.out.println("the amount of cols containing zeros = " + count); 
    } 
} 

出力:

3, 0, 0, 6, 
4, 0, 1, 0, 
the amount of rows containing zeros = 2 
the amount of cols containing zeros = 3 

http://ideone.com/VE0qAw

+0

多くの感謝!シンプルで完璧ですが、なぜそれが正方行列に適していると書いていますか? –

+0

行列がない場合、ループは境界外の例外を迂回するでしょう – ritesht93

+0

申し訳ありませんが、多分私は理解できませんでしたが、私の配列(行列)は正方形ではありませんが、あなたのメソッドはまだ動作します!私はGoogleの翻訳者を使用し、翻訳の微妙な部分をキャッチしないかもしれません:)私はこのサイトのロシア語版で私の質問にあなたの解決策を共有しました。再度、感謝します。 –