java - Reformatting source code with Text I/O -
i teaching myself programming java through textbook. exercise asks write program reformats entire source code file (using command line):
from format (next-line brace style):
public class test { public static void main(string[] args) { // statements } }
to format (end-of-line brace style):
public class test { public static void main(string[] args) { // statements } }
here's code have far:
import java.io.*; import java.util.*; public class fourteenpoint12 { public static void main(string[] args) throws ioexception { if (args.length != 2) { system.out.println ("usage: java fourteenpoint12 sourcefile targetfile"); system.exit(1); } file sourcefile = new file(args[0]); file targetfile = new file(args[1]); if (!sourcefile.exists()) { system.out.println("file not exist"); system.exit(2); } scanner input = new scanner(sourcefile); printwriter output = new printwriter(targetfile); string token; while (input.hasnext()) { token = input.next(); if (token.equals("{")) output.println("\n{\n"); else output.print(token + " "); } input.close(); output.close(); }
}
i have 2 problems:
i have tried many different while blocks, can't close book asking. i've tried different combinations of regular expressions, delimeters, token arrays, still way off.
the book asks reformat single file, chapter never explained how that. explains how rewrite text new file. wrote program create new file. way problem asks.
if me these 2 problems, solve many of problems i'm having alot of exercises. in advance.
this feasible simple regular expression.
you want replace ) *any whitesplace character* {
) {
.
in java regex, there predefined regex : \s
matches whitespace characters : [ \t\n\x0b\f\r]
here, want replace )\s*{
) {
.
to achieve this, load whole file in string (called input
below) , use string#replaceall(string regex, string replacement) :
//added escape characters... input.replaceall("\\)\\s*\\{", ") {");
test :
string input = "public static void main() \n {"; system.out.println(input.replaceall("\\)\\s*\\{", ") {"));
output :
public static void main() {
Comments
Post a Comment