2017-09-13 135 views
0

字符串分割數量不明的我有結構化的這樣一個文本文件:爪哇 - 每行

class Object0 extends Object1 
    class Object2 extends Object3 
    class Object1 
    class Object4 extends Object1 
    class Object3 

我想要分割每個字符串,並將其存儲。我知道如何在每行上已知字符串數量的情況下執行此操作,但在這種情況下,給定行上可能有兩個或四個字。

這裏就是我有分裂時的已知串的數量:

public static void main(String[] args) { 

     try { 
      File f = new File("test.txt"); 
      Scanner sc = new Scanner(f); 
      while(sc.hasNextLine()){ 
       String line = sc.nextLine(); 
       String[] details = line.split(" "); 
       String classIdentifier = details[0]; 
       String classNameFirst = details[1]; 
      // String classExtends = details[2]; 
      // String classNameSecond = details[3]; 
      } 
     } catch (FileNotFoundException e) {   
      e.printStackTrace(); 
     } 
+1

使用'details.length'來檢查它是否是2或4 – daniu

+0

什麼是你的定義了'工作代碼? – Incognito

回答

1

您可以在details陣列上的循環來獲取每個分裂串不管他們有多少人。另外,我對main方法做了一些更改,使其更加正確(添加了finally子句以關閉Scanner資源)。

public static void main(String[] args) { 

    Scanner sc = null; 
    try { 
     File f = new File("test.txt"); 
     sc = new Scanner(f); 
     while(sc.hasNextLine()){ 
      String line = sc.nextLine(); 
      String[] details = line.split(" "); 
      for(String str: details) { 
       //variable str contains each value of the string split 
       System.out.println(str); 
      } 
     } 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } finally { 
     sc.close(); 
    } 
} 
0

在每次迭代中,你可以檢查,如果有兩個以上的話,是這樣的:

public static void main(String[] args) { 

    try { 
     File f = new File("test.txt"); 
     Scanner sc = new Scanner(f); 
     while(sc.hasNextLine()){ 
      String line = sc.nextLine(); 
      String[] details = line.split(" "); 
      String classIdentifier = details[0]; 
      String classNameFirst = details[1]; 
      // this can be done because you declared there 
      // can be only 2 or 4 words per line 
      if (details.length==4) { 
       String classExtends = details[2]; 
       String classNameSecond = details[3]; 
      } 
      // do something useful here with extracted fields (store?) 
      // before they get destroyed in the next iteration 
     } 
    } catch (FileNotFoundException e) {   
     e.printStackTrace(); 
    } 
}