2013-07-21 139 views
0

輸入解析的文本文件分爲兩個部分(空白分隔):如何使用掃描儀

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

我想處理這些輸入像:

對於在文本文件中的每一行: :(first_element,例如,1)轉換成一個int變量(比如,m)和下述(next_elements,例如1 2 3)轉換成一個ArrayList(比方說,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); 
    } 
    } 

但我無法解析輸入,因爲我打算。有關如何使用掃描儀處理輸入行兩部分的任何建議?或者,甚至如何檢查當前行結束(EOL)以及如何更輕鬆地解析第一個元素?

回答

1

在您的代碼中嘗試使用此String[] line = file_scanner.nextLine().split("\\s+",2);。它會將每行分成2個令牌。

編輯:行[1]將包含其餘的數字,你不需要再次解析它。

+0

非常感謝!它現在拯救了我的生命:) – joarderm

0

對不起它可能不是最有效的,因爲它是上午4:39:

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