So after scanning a file, I am to format it and output it following these guidelines:

-Lines are trimmed to remove any leading or trailing white space. Note that String has a
method trim() that removes leading/trailing white space.
 A trimmed line is displayed with X leading spaces
 The initial value for X is 0
 If a ‘{‘ appears on a line then X is increased by 4 and this affects the display of subsequent
lines
 If a ‘}’ appears on a line then X is decremented by 4 and this affects the display beginning
with the current line.
-The effect of this processing is similar to that done by the Auto-layout option in BlueJ.

My code so far is as follows:

public class PrettyPrint
{
   public static void main (String[] args) throws IOException

   {
       String spaces = "";

       Scanner kb = new Scanner(System.in);

       System.out.println("Please enter the name of the file you wish to format");

       String fileName = kb.nextLine();

       File file = new File(fileName);
       Scanner inputFile = new Scanner(file);

       while (inputFile.hasNextLine())
       {
           String line = inputFile.nextLine();
           line.trim();

           if (line.contains("{"))
            {
                spaces += "    ";
                line = spaces + line;
            }
           System.out.println(line);
       }
   }
}

The program is far from finished as you can see because I've run into a problem already. I was able to successfully add 4 spaces onto the line that contained the "{", however, it only affected that line alone. The rest of the lines after it had no added spaces. After looking back on the program I can see why. The issue is that I have no idea how to fix this. Any ideas?

Dani AI

Generated

Two quick diagnostic points that explain why your output didn’t keep the extra indentation: calling line.trim() returns a new String (it does not modify line) and building a spaces string only when you hit the brace line doesn’t maintain a numeric indentation state for subsequent lines. Treat indentation as a numeric state (e.g., int indent) that you update and carry across lines. Because a closing brace should affect the current line, decrement before printing; because an opening brace affects later lines, increment after printing.

// compact approach (Java 11+ uses String.repeat)
int indent = 0;
while (input.hasNextLine()) {
    String line = input.nextLine().trim();         // reassign trimmed value

    int closes = countChar(line, '}');
    indent = Math.max(0, indent - 4 * closes);    // apply '}' before printing

    String pad = " ".repeat(indent);               // or build a char[] if < Java 11
    System.out.println(pad + line);

    int opens = countChar(line, '{');
    indent += 4 * opens;                           // apply '{' for subsequent lines
}

// helper
private static int countChar(String s, char ch) {
    int c = 0;
    for (int i = 0; i < s.length(); i++) if (s.charAt(i) == ch) c++;
    return c;
}

Tips and edge cases: if a line contains multiple braces this counts each one; protect against negative indent with Math.max. If braces can appear inside string literals or comments, a simple count will misfire—either strip quoted text first or implement a tiny state machine that ignores characters inside quotes. If you need compatibility with older Java, build pad with a filled char[] or a StringBuilder loop instead of String.repeat.

This follows the state idea suggested but uses a numeric indent (simpler and safer than repeatedly appending to a spaces string) and fixes the trim() oversight from .

Recommended Answers

All 4 Replies

if you want to add spaces on every line, why add the if statement?

if (line.contains("{"))
{
spaces += " ";
line = spaces + line;
}

in the first line, you are telling your application only to run the two lines within the block, if the line contains "{". if you want it to perform on all the lines, drop the if statement.
replace the above with:

spaces += " ";
line = spaces + line;

Sorry, I wasn't being clear enough. In the guidelines it says that I must add 4 white spaces when I encounter a "{" and I must decrease by 4 white spaces when I encounter a "}". Before I was able to code for what happens when I encounter the "}", I had a problem with the "{" already. It's supposed to add 4 white spaces to that line and all other subsequent lines until it encounters the "}", in which case it will take away 4 white spaces. However, while scanning for the "{" and adding the white spaces when i encounter it, it only affects that particular line.

as I pointed out, you coded it the way that only that one line will have four additional spaces.

what you can do, is keep an additional value deciding whether or not to add spaces.

so:

boolean addSpaces = false;
while (inputFile.hasNextLine())
{
String line = inputFile.nextLine();
line.trim();
if (line.contains("{"))
{ addSpaces = true;
}
if ( addSpaces ){
spaces += " ";
line = spaces + line;
}
if ( line.contains("}"){
addSpaces = false;
}
System.out.println(line);
}

if your line containing the '}' should not have the additional spaces, you'll need to move the last if statement above the if ( addSpaces ) block.

Thanks, that really helped me out.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.