2015-10-06 31 views
1

串聯一系列字符串有一點問題。試圖通過數組

String A = "A /n" 
String A = "A /n U /n" 
String A = "A /n U /n B /n" 

:我通過在那裏通過我想篩選出一系列的文本,並在每個循環,然後最終落得在循環階段,即訂購結束將它們連接起來它下面的一個文件循環等...

的輸出將是

ù

不過,我想這是

一個

ü

我到目前爲止做了以下:

public static void organiseFile() throws FileNotFoundException { 
    ArrayList<String> lines = new ArrayList<>(); 
    ArrayList<String> order = new ArrayList<>(); 
    String directory = "C:\\Users\\xxx\\Desktop\\Files\\ex1"; 
    Scanner fileIn = new Scanner(new File(directory + "_ordered.txt")); 
    PrintWriter out = new PrintWriter(directory + "_orderesqsd.txt"); 
    String otherStates = ""; 

    while (fileIn.hasNextLine() == true) { 
     lines.add(fileIn.nextLine()); 
     System.out.println("Organising..."); 
    } 
    Collections.sort(lines); 
    for (String output : lines) { 
     if (output.contains("[EVENT=agentStateEvent]")) { 
      out.println(output + "\n"); 
      out.println(otherStates + "\n"); 
      otherStates = ""; 
     } 
     else { 
     otherStates += output+ "\n";  
    } 
    out.close(); 
} 

現在這樣做輸出正常,但是,關於「otherStates」,我想以數字順序得到這個,我知道的最好的方法是使用Collections,但是是爲數組。我不確定如何去修改代碼的「otherStates」部分,以迎合連接字符串的數組,然後能夠相應地對它們進行排序。任何想法

+0

你提的問題是非常不清楚的一些想法 - 「我想在某一爲了得到這個」不解釋你想要的所有東西訂購。爲什麼你把'otherStates'作爲一個單獨的字符串而不是某種類型的集合?如果你想重新排序,收集所有元素作爲一個集合,排列它們,然後*然後*將它們連接在一起... –

+0

這是我掙扎的地方。我知道其他狀態需要從一個字符串更改爲一個數組,所以我可以使用collections.sort命令。我有一個叫做「order」的數組,但是我不能簡單地用「order」來替換「otherStates」。 –

+1

您沒有任何陣列。你有ArrayLists。他們不是一回事。但是你可以爲'otherStates'創建第三個ArrayList,並添加到它而不是使用字符串連接 - 什麼阻止你這樣做? –

回答

1

難以提供沒有輸入文件數據的正確解決方案。只需嘗試下面的代碼。至少,它應該給你如何解決這個問題

public static void organiseFile() throws FileNotFoundException { 
ArrayList<String> lines = new ArrayList<>(); 
ArrayList<String> order = new ArrayList<>(); 
String directory = "C:\\Users\\xxx\\Desktop\\Files\\ex1"; 
Scanner fileIn = new Scanner(new File(directory + "_ordered.txt")); 
PrintWriter out = new PrintWriter(directory + "_orderesqsd.txt"); 

String otherStates = ""; 
ArrayList<String> otherStates_duplicate = new ArrayList<>(); 
String ordered_new_string.; 

while (fileIn.hasNextLine() == true) { 
    lines.add(fileIn.nextLine()); 
    System.out.println("Organising..."); 
} 
Collections.sort(lines); 
for (String output : lines) { 
    if (output.contains("[EVENT=agentStateEvent]")) { 
     out.println(output + "\n"); 
     out.println(otherStates + "\n"); 
     otherStates = ""; 
    } 
    else { 
    otherStates += output+ "\n"; 
    otherStates_duplicate.add(output); 

} 
Collections.sort(otherStates_duplicate); // Now this should have a sorted list 

//if you need a string instead of an arraylist use code below in addition 
for(String s:otherStates_duplicate){ 

ordered_new_string += s + "\n"; 

} 

/* 
I have not printed or stored the string ordered_new_string as it is not 
clear to me what you want. print/write to a file and check 
if ordered_new_string is what your required 

*/ 

out.close(); 
}