2014-01-16 64 views
1

在Java中,我試圖從一個ArrayList(稱爲filesToReport)將字符串連接成單個字符串,因爲我想在單個錯誤消息中顯示所有文件名一個對話框,如果它們不匹配文件開啓器中的某些標準。我現在使用的解決方案是一個StringBuilder,原則上它可以工作。但是,問題是,如果我例如。打開三個不符合條件的文件,我首先獲得一個文件列表文件號。 1,然後一個箱子列出文件沒有。 1和2,然後最後一個盒子列出文件號碼。 1,2和3.最後一個盒子是我想要的單個盒子。有沒有辦法做到這一點?使用StringBuilder將字符串的ArrayList連接成一個字符串

我的解決方案至今看起來如下:

if(filesToReport.size() > 0) { 
    StringBuilder sb = new StringBuilder(); 

    for(String fileToReport : filesToReport) { 
     sb.append(fileToReport).append(","); 
    } 

    String incompatibleFiles = sb.toString(); 
    String errorMessage = "The following files were not loaded \n" + 
          "as the are incompatible: \n" + 
          incompatibleFiles; 
    JOptionPane.showMessageDialog(frame, errorMessage); 
} 
+4

您描述的行爲不是您發佈的代碼的行爲。 –

+0

林不知道我理解的問題,但我認爲,如果filesToReport將HashSet而不是ArrayList,你會避免這種行爲,因爲集只會包含唯一的字符串。 – Divers

+0

我同意Marko Topolnik,你的解決方案工作正常,據我所知... – Enerccio

回答

1

我看不到這個代碼snipplet的問題,但我的猜測是,你正在追加錯誤消息相同filesToReport列表。所以它會包含以前的錯誤信息。

+0

乾杯......我已經無意地把這個塊放在另一個for語句。有時候,只要有新鮮的眼睛看代碼就可以了:) – SorenRomer

+0

Upvote and/or Accept? –

1

正如你在這裏張貼,你可能已經糾正了錯誤。您所描述的行爲將已造成錯位的括號:

if(filesToReport.size() > 0) { 
    StringBuilder sb = new StringBuilder(); 

    for(String fileToReport : filesToReport) { 
     sb.append(fileToReport).append(","); 

    String incompatibleFiles = sb.toString(); 
    String errorMessage = "The following files were not loaded \n" + 
          "as the are incompatible: \n" + 
          incompatibleFiles; 
    JOptionPane.showMessageDialog(frame, errorMessage); 
    } 
} 
相關問題