private static void doOptionTwo(int balance) throws IOException {
JOptionPane.showMessageDialog(null, "Option two selected ");
String sum = null;
BufferedReader br = null;
br = new BufferedReader(new FileReader("file1.txt"));
for (int i = 1; i <= 6; i++){
String line1 = br.readLine();
//JOptionPane.showMessageDialog(null, line1);
sum = sum + line1;
}
if (br != null)br.close();
String log = sum;
JOptionPane.showMessageDialog(null, log);
}
答案 0 :(得分:3)
使用StringBuilder而不是初始化为null的String。您可以使用以下代码执行任何操作:
StringBuilder stringBuilder = new StringBuilder();
String newLineCharacter = System.getProperty("line.separator");
for (int i = 1; i <= 6; i++){
stringBuilder.append(br.readLine());
stringBuilder.append(newLineCharacter);//note: will add new line at end as well..
}
答案 1 :(得分:1)
每次在String中插入break:
for (int i = 1; i <= 6; i++) {
String line1 = br.readLine();
sum += line1 + "\n";
}
答案 2 :(得分:1)
您只需在行之间添加"\n"
即可。
String sum = "";
for (int i = 1; i <= 6; i++){
String line1 = br.readLine();
sum += line1 + "\n";
}
或者更合适的是,使用StringBuilder
。
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 6; i++){
String line1 = br.readLine();
if (sb.length() > 0) {
sb.append('\n');
}
sb.append(line1);
}
String sum = sb.toString();
答案 3 :(得分:0)
这更有效:
JOptionPane.showMessageDialog(null, "Option two selected ");
StringBuilder build = new StringBuilder();
BufferedReader br = null;
br = new BufferedReader(new FileReader("file1.txt"));
for (int i = 1; i <= 6; i++){
String line1 = br.readLine();
//JOptionPane.showMessageDialog(null, line1);
build.append(sum).append("\n");
}
if (br != null)br.close();
System.out.println(build.toString());