2016-03-28 78 views
0

用戶輸入數字,每行最多20個,最多50行。問題是,如果用戶在一行中輸入少於20個整數,則該數組在空白處填充零,以便總共有20個整數。這會影響我對數組的計算。擺脫二維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

如爪哇labguage Specifications提到的,陣列的所有元件將用「0」值,如果數組是int類型的初始化。

但是,如果你想0區分是由用戶輸入和默認分配0,我會建議使用Integer類的陣列,使所有的值與null初始化,儘管這將需要改變代碼(即檢查nullint字面鑄造前),例如:

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

在您藤創建的ArrayList,而不是二維數組的ArrayList的這種情況。

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

現在,您可以根據輸入值dynamicaly賦值,所以加入到數據沒有多餘的零,如果它含有小於20連勝。

2

您應該查看List s。既然你承認你不知道要插入多少元素,我們可以根據用戶想要添加的許多內容簡單地列出列表。

// 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時,你只需要停下來,或者超過輸入的數量。