Question

The goal of this code is to read a file and add numbers to the end of every {(curly bracket) but the file does not output each line like it does in the file but it out puts it into one entire line. where do I put a System.out.println statement. I tried every where and it keeps repeating it

 import java.io.File;
 import java.io.FileNotFoundException;
 import java.util.Scanner;

public class Test {

public static void main(String args[]) {

        readFile();
}

public static void readFile() { // Method to read file

    Scanner inFile = null;
    String out = " ";

    try {
        Scanner input = new Scanner(System.in);
        System.out.println("enter file name");
        String filename = input.next();
        File in = new File(filename); // ask for the file name
        inFile = new Scanner(in);



        int count = 0;
        while (inFile.hasNextLine()) { // reads each line
            String line = inFile.nextLine();
            for (int i = 0; i < line.length(); i++) {

              char ch = line.charAt(i);
                out = out + ch;

                if (ch == '{') {
                    count = count + 1;                         
                    out = out + " " + count + " ";
                } else if (ch == '}') {
                    out = out + " " + count + " ";
                    if (count > 0) {
                        count = count - 1;

                    }
                }
            }
        }

        System.out.println(out);

    } catch (FileNotFoundException exception) {
        System.out.println("File not found.");
    }
    inFile.close();
}
}
Was it helpful?

Solution

where do I put a System.out.println statement

The entire output is built in a single string that is not printed until the end, so adding System.out.println statements in the line loop won't help. You can add line breaks to the string by doing:

out += "\n";

Or, at the end of the body of your line loop, print the current line, and reset the buffer for the next line:

System.out.println(out);
out = "";

Using a String for the output buffer is not efficient by the way. String is immutable, so every + statement is copying and duplicating all of the previous characters to create a new object, every time. Consider declaring out as a StringBuilder rather than a String. Then you can add to it with the .append() method and it will not copy all the text every time because a StringBuilder is mutable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top