2016-03-28 13 views
0

ユーザーは、行と行ごとに最大20の数値を入力します。問題は、ユーザーが1行に20未満の整数を入力した場合、空のスペースに0が埋められ、合計が20になるということです。これは、配列で行った計算に影響を与えます。2d Java配列の自動塗りつぶしゼロを取り除く

誰も、元の入力番号だけが残るようにそれらのゼロを取り除く効率的な方法を知っていますか?

//Extracting/reading from file 
public void readFile(File file) { 

    try { 
     //creates scanner to read file 
     Scanner scn = new Scanner(file); 

     //set initial count (of rows) to zero 
     int maxrows = 0; 

     //sets columns to 20 (every row has 20 integers - filled w zeros if not 20 inputted) 
     int maxcolumns = 20; 

     // goes through file and counts number of rows to set array parameter for length 
     while (scn.hasNextLine()) { 
      maxrows++; 
      scn.nextLine(); 
     } 

     // create array of counted size 
     int[][] array = new int[maxrows][maxcolumns]; 

     //new scanner to reset (read file from beginning again) 
     Scanner scn2 = new Scanner(file); 

     //places integers one by one into array 
     for (int row = 0; row < maxrows; row++) { 
      Scanner lineScan = new Scanner(scn2.nextLine()); 
      //checks if row has integers 
      if (lineScan.hasNextInt()) { 

       for (int column = 0; lineScan.hasNextInt(); column++) { 
        array[row][column] = Integer.parseInt(lineScan.next()); 
       } 

      } else System.out.println("ERROR: Row " + (row + 1) + " has no integers."); 
     } 
     rawData = array; 
    } 
} 
+0

コードはどこですか?どのように整数を配列内の行に変換しますか? – Marc

+1

2D配列ではなく、配列の配列と考えることができます。どのくらいの大きさが必要かを知っている場合にのみ、各行を作成してください。 –

+0

@Marcがコードを更新しました –

答えて

0

のJava labguage Specificationsで述べたように、アレイのタイプintである場合、アレイのすべての要素が「0」の値で初期化されます。あなたは、ユーザによって入力され、デフォルトで割り当てられている0こと0を区別したい場合は、すべての値がnullで初期化されるように、それがで変える必要があるだろうが、

しかし、私は、Integerクラスの配列を使用することをお勧めしますコード(すなわち、リテラルintでそれをキャストする前にnull値をチェックするために)、例えば:その場合は

Integer[][] array = new Integer[maxrows][maxcolumns]; 
0

あなたがcanyのArrayListのArrayListの代わりに2D配列を作成します。それは行の20未満を含む場合

ArrayList<ArrayList<Integer>> group = new ArrayList<ArrayList<Integer>>(maxrows); 

今度はdynamicaly入力値に基づいて値を割り当てることができるので、余分なゼロは、データに加えられません。

2

代わりにListを調べる必要があります。いくつの要素が挿入されるのかわからないので、ユーザーが追加したいことがたくさんあるだけで、リストを拡張することができます。

// Initialize the initial capacity of your dataMatrix to "maxRows", 
// which is NOT a hard restriction on the size of the list 
List<List<Integer>> dataMatrix = new ArrayList<>(maxrows); 

// When you want to add new elements to that, you must create a new `List` first... 

for (int row = 0 ; row < maxrows ; row++) { 
    if (lineScan.hasNextInt()) { 
     List<Integer> matrixRow = new ArrayList<>(); 
     for (int column = 0; lineScan.hasNextInt(); column++) { 
      dataMatrix.add(Integer.parseInt(lineScan.next())); 
     } 
     // ...then add the list to your dataMatrix. 
     dataMatrix.add(matrixRow); 
    } 
} 
0

さまざまな整数が必要な場合は、通常、ArrayList<Integer>を使用します。

配列が必要な場合は、-1をすべて-1に設定するか(-1が無効/センチネル入力の場合)、またはユーザーが数字を何回入力したかをカウントします。その後、-1に達すると停止するか、入力数を超えなければなりません。

関連する問題