2013-07-21 2 views
0
에게

입력을 사용하여 두 부분으로 텍스트 파일을 구문 분석 (공백으로 구분) : 텍스트 파일의 각 라인에 대한방법 스캐너

:

1 1 2 3 
2 1 7 
3 3 7 
4 1 5 
5 3 6 

가 나는 등 같은 이러한 입력을 처리하고 싶습니다 : (first_element 예 1)는 INT 변수 (예를 들어, m)과의 ArrayList에 다음 (next_elements 예 1 2 3) (예를 들어, N)이

제가 아래의 시도로 :

Scanner file_scanner = new Scanner(filename); 
    while (file_scanner.hasNextLine()) {    
    String[] line = file_scanner.nextLine().split("\\s+"); 
    String str1 = line[0]; 
    String str2 = line[1]; 

    m = Integer.parseInt(str1); 

    Scanner line_scanner = new Scanner(str2); 
    while(line_scanner.hasNext()) { 
     int n = line_scanner.nextInt(); 
     N.add(n); 
    } 
    } 
,

하지만 의도 한대로 입력을 구문 분석 할 수 없습니다. Scanner를 사용하여 입력 라인의 두 부분을 처리하는 방법에 대한 제안이 있습니까? 또는 심지어 현재 줄 (EOL)의 끝을 확인하는 방법과 첫 번째 요소를 더 쉽게 파싱하는 방법도 있습니다.

답변

1

코드를 사용해보십시오. String[] line = file_scanner.nextLine().split("\\s+",2);. 각 행을 2 개의 토큰으로 분할합니다.

EDIT : line [1]은 나머지 숫자를 포함하므로 다시 구문 분석 할 필요가 없습니다. 그것은 오전 4:39 이후

+0

감사합니다 많이! 그것은 내 인생을 지금 저장합니다 :) – joarderm

0

죄송이 가장 효율적으로되지 않을 수 있습니다

Scanner s = new Scanner(file); 
    int m = 0; 
    List<Integer> list = null; 

    while(s.hasNextLine()) 
    { 
     Scanner s2 = new Scanner(s.nextLine()); 
     int count = 0; 

     list = new ArrayList<Integer>(); 
     while (s2.hasNextInt()) 
     { 

      if(count == 0) 
      { 
       m = s2.nextInt(); 
      } 
      else 
      { 
       list.add(s2.nextInt()); 
      } 
      count++; 
     } 
     System.out.println(m + " " + list); 
    }