Oneinchwalrus
Oneinchwalrus

Reputation: 71

Making bufferedreader from loop, to next line?

sorry about the poor title, didn't quite know what to call it! basically I made the loop below to show the first six lines from the file, got that sorted. When it comes to showing the six lines though, I'm not sure how to get them to appear on a different line each time. The closest I got, was including the joptionpane in the loop, showing one line, then on the next joptionpane on the next et al. The second joptionpane at the bottom shows all the lines but on the same line instead of the next etc. How ought I make it so they appear on the next line each time? \n doesn't seem to work.

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);

}

Upvotes: 0

Views: 290

Answers (4)

neferpitou
neferpitou

Reputation: 1672

This is more efficient :

    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());

Upvotes: 0

khelwood
khelwood

Reputation: 59111

You can just add "\n" between the lines.

String sum = "";
for (int i = 1; i <= 6; i++){
    String line1 = br.readLine();
    sum += line1 + "\n";
}

Or more appropriately, use a 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();

Upvotes: 1

SMA
SMA

Reputation: 37033

Use StringBuilder instead of String which is initialized as null. You could do whatever you want with following code:

 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..
}

Upvotes: 3

Abdelrahman Elkady
Abdelrahman Elkady

Reputation: 2576

Just insert break each time in your String :

for (int i = 1; i <= 6; i++) {
    String line1 = br.readLine(); 
    sum += line1 + "\n";
}

Upvotes: 1

Related Questions