2017-12-31 170 views
-4

나는 운동을위한 자바에서 다음 코드를 작성 :Integer 배열에 "null"이 포함 된 텍스트 파일을 읽는 방법은 무엇입니까?

배열이 .txt 파일에서 읽을 수 있도록 내가 코드를 다시 작성할 필요
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; 
    } 
} 

:

1 
2 
3 
null 
22 
41 
52 
61 
10 

내가 작성하는 방법을 알고 모든 항목이 정수인 경우 코드. 그러나 파일 중 하나가 .txt 파일에서 "null"인 경우 어떻게 코드를 다시 작성해야합니까? 내가 코멘트에서 언급 한 바와 같이

+2

문자열로 모든 정수를 읽어보세요! string에 "null"이 있으면 array에'null'을 넣고, 그렇지 않으면 정수를 배열에 넣습니다 (string을 정수로 변환 한 후). –

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