2017-12-31 181 views
-4

は、私は運動のためにJavaで次のコードを書いた:"null"を含むテキストファイルをInteger配列に読み込む方法は?

public class myTest { 
    public static void main(String[] args) { 
     Integer[] a = new Integer[10]; 
     a[0] = 1; 
     a[1] = 2; 
     a[2] = 3; 
     a[4] = null; 
     a[5] = 22; 
     a[6] = 41; 
     a[7] = 52; 
     a[8] = 61; 
     a[9] = 10; 
     int n = 10; 
     for (int i = 0; i < n; i++) { 
      if (a[i] == null) { 
       throw new IllegalArgumentException("Illiegal argument"); 
      } 
     } 
     // something else here; irrelevant to the question; 
    } 
} 

Iが配列の.txtファイルから読み込むことができるようにコードを書き直す必要があります。

1 
2 
3 
null 
22 
41 
52 
61 
10 

私が書く方法を知っていますすべてのエントリが整数のときのコードしかし、いずれかが.txtファイルで "null"の場合、コードをどのように書き直すべきですか?私はコメントで述べたように

+2

を文字列としてすべての整数を読みます!文字列が "null"の場合は、配列に 'null'を入れ、そうでなければ、整数を配列に入れます(文字列を整数に変換した後)。 –

+0

このメソッドはテストすると正確には何か、つまりテスト対象のユニットは何ですか? – Turing85

+0

なぜあなたはそれらをオブジェクトとして書きませんか? –

答えて

0

、次のようにコーディングすることができます:

public static void main(String[] args) { 

    BufferedReader r = new BufferedReader(new FileReader("input.txt")); 
    String line; 
    // Assuming you have 10 integers in the file 
    // If the number of integers is variable you can use a List instead of an array and dynamically add to the list 
    Integer a[] = new Integer[10]; 
    int i = 0; 
    while((line = r.readline()) != null) { 
     // If there is a blank line in the file, just skip it 
     if(line.trim().isEmpty()) continue; 
     // If line in the file contains "null" then put null in a[i] 
     if(line.trim().equals("null") { a[i] = null; i++; } 
     // Else, convert to integer and put that integer in a[i] 
     else { a[i] = Integer.parseInt(line.trim()); i++; } 
    } 
    try { 
     // Check for null and throw exception if encountered 
     for(int i = 0; i < 10; i++) { 
      if(a[i] == null) throw new IllegalArgumentException("Illegal Argument");  
     } 
    } 
    catch(IllegalArgumentException e) { 
      System.out.println(e); 
    } 
} 
関連する問題