2017-12-31 89 views
-4

Ich schrieb den folgenden Code in Java für eine Übung:Wie lese ich eine Textdatei, die "null" enthält, in ein Ganzzahl-Array?

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; 
    } 
} 

Ich brauche den Code neu zu schreiben, so dass das Array von einer .txt Datei gelesen werden kann:

1 
2 
3 
null 
22 
41 
52 
61 
10 

Ich weiß, wie zu schreiben der Code, wenn alle Einträge Ganzzahlen sind. Aber wenn einer von ihnen "Null" in der .txt Datei ist, wie sollte ich den Code umschreiben?

+2

jede ganze Zahl als String lesen! Wenn string "null" hat, dann setze 'null' in array, ansonsten setze die ganze Zahl in das array (nach dem Konvertieren von string in integer). –

+0

Was genau soll diese Methode testen, d. H. Was ist die zu testende Einheit? – Turing85

+0

warum schreibst du sie nicht als Objekt. –

Antwort

0

Wie ich im Kommentar erwähnt, können Sie Code wie folgt:

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); 
    } 
} 
Verwandte Themen