2013-05-23 2 views
0

"cool.txt"파일의 항목과 "warm.txt"라는 텍스트 파일을 제외하고는 배열에 대해 동일한 문자열 배열을 인스턴스화하려고합니다. 범위 그러나 배열의 많은 요소는 이것처럼 null로 레이블이 붙어 있습니다. enter image description here2 개의 텍스트 파일에서 2 개의 배열을 인스턴스화

배열에 모든 올바른 항목이 있으므로 부분적으로 정확합니다.

후 널 (null)의 단지 수백만 여기 당신이 list 객체로 변환 결국 함수의 끝에서 내 코드

int count2=0; 
    int count3=0; 
    String[] filename ={"Cool.txt","Warm.txt"}; 
    String[] cool =new String[30]; 
    String[] warm =new String [3000]; 
    String[][] arrays = new String [][]{cool,warm}; 
    BufferedReader fr; 



    try 
    { 
    for(int i=0; i<2; i++) 
    { 
    fr = new BufferedReader(new FileReader(filename[i])); 
    String line = fr.readLine(); 

    while (line != null) 
      { 

       if (i<=0) 
       {arrays[i][count2]=line; 
       System.out.println("COOL");  
       count2++;} 

     if(i>=1) 
     {arrays[i][count3]=line; 
     System.out.println("WARM");  
     count3++;} 

     line = fr.readLine(); 

} 
    fr.close(); 


    } 

    System.out.println(Arrays.asList(warm)); 
    System.out.println(Arrays.asList(cool)); 
    } 




      catch(Exception F){ 
     System.out.println("NUL"); 
    } 

} 

답변

2

Java에서 개체 배열을 만들면 기본값으로 초기화됩니다. 정수의 경우 0입니다. String과 같은 객체의 경우 null 참조입니다. 배열에 30000 개의 요소가 포함되어 있으므로 파일의 요소 (약 5 개)가 있고 나머지는 초기화되지 않습니다 (null).

가변 크기의 개체 목록을 사용하려는 경우 ArrayList 또는 다른 유형의 목록을 조회 할 수 있습니다. 당신이 인 경우에 다음과 같은 라인을 교체 :

String[] cool =new String[30]; 
String[] warm =new String [3000]; 

System.out.println(Arrays.asList(warm)); 
System.out.println(Arrays.asList(cool)); 

System.out.println(warm); 
System.out.println(cool); 
List<String> cool = new ArrayList<String>(); 
List<String> warm = new ArrayList<String>(); 

당신은 올바른 결과를 얻을 것입니다. 이미 목록을 사용하고있었습니다. Arrays.asList 메서드 호출은 형식을 List 형식의 개체로 변환합니다.

+0

오, 정말 고맙습니다. 완벽하게 일했습니다 – nmu

+0

괜찮습니다! Java 7을 사용하는 경우에는 new ArrayList ();에서 'String'을 반복하지 않아도됩니다. 'List cool = new ArrayList <>();'라고 쓰면 자바가 어떤 유형인지 알아낼 것이다. 다이아몬드 운전사라고합니다. 적은 시간을 절약하면 시간을 절약하는 데 유용합니다! – RaptorDotCpp

+0

그래, 난 사실 infact 나는 수동 배열 인쇄 문을 사용하고 배열을 문자열로 남겼습니다. – nmu

0

입니다. 처음에 List을 사용하면 "수백만"의 null이 발생하지 않습니다. null을 얻는 이유는 배열을 한 번만 할당 할 수 있기 때문에 모든 슬롯의 기본값은 null입니다.

관련 문제