2017-09-13 213 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(); 
    } 
}