user3278117
user3278117

Reputation: 95

Reformatting Java Source Code, instead of next line use end of line curly braces

I've been trying to figure out how to implement a problem (linked further down) but, I'm hitting a wall.

Basically I have to reformat source code that uses next line curly braces to end of line curly braces. For some reason, the professor for my class decided to assign this problem in our Strings chapter and not in the Text I/O chapter (which is about 5 chapters later).

String sourceString = new String(Files.readAllBytes(Paths.get("Test.txt")));
String formatted = sourceString.replaceAll("\\s\\{", "\\{");
System.out.println(formatted);

So that's what I have so far. When I do a run, the output is the same as the source file. I followed this problem and using an idiom I found to convert all of the file into a String, the replaceAll method stopped... replacing.

While I still had it set up like this

StringBuilder source = new StringBuilder();
    while(s.hasNext()){
        source.append(s.nextLine());
    }
    String sourceString = source.toString();
    String formatted = sourceString.replaceAll("\\)\\s*\\{", ") {");
    System.out.println(formatted);

the output is all on a single line. I feel like the replaceAll method isn't occurring at all. I feel like I'm forgetting something blatantly obvious.

Upvotes: 0

Views: 1213

Answers (2)

Braj
Braj

Reputation: 46841

If you want to do it without using replaceAll() and regex then try this one:

    String nextLine = null;
    String currentLine = null;
    while (s.hasNext()) {
        currentLine = s.nextLine();
        if (currentLine.trim().endsWith(")")) {
            while(s.hasNext()){
                if((nextLine = s.nextLine()).trim().length() != 0){
                    break;
                }
            }

            if (nextLine.trim().equals("{")) {
                source.append(currentLine).append(" {").append("\n");
            } else {
                source.append(currentLine).append("\n");
            }

        } else {
            source.append(currentLine).append("\n");
        }
    }

Upvotes: 0

wvdz
wvdz

Reputation: 16641

The second argument of replaceAll() is a String, not a regex, so no need to escape the { there.

Also add a + to denote one or more whitespaces.

So:

sourceString.replaceAll("\\s+\\{", "{")

Upvotes: 1

Related Questions