Monday, 26 August 2013

Reformatting source code with Text I/O

Reformatting source code with Text I/O

I am teaching myself programming with Java through a textbook. An exercise
asks you to write a program that reformats an entire source code file
(using the command line):
from this format (next-line brace style):
public class Test
{
public static void main(String[] args)
{
// Some statements
}
}
to this format (end-of-line brace style):
public class Test {
public static void main(String[] args) {
// Some statements
}
}
Here's the code I have so 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 does 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 two problems:
I have tried many different while blocks, but can't get anything close to
what the book is asking. I've tried different combinations of regular
expressions, delimeters, token arrays, but still way off.
The book asks you to reformat a single file, but the chapter never
explained how to do that. It only explains how to rewrite the text into a
new file. So I just wrote the program to create a new file. But I would
really like to do it the way the problem asks.
If someone could help me with these two problems, it would actually solve
many of the problems I'm having with alot of the exercises. Thanks in
advance.

No comments:

Post a Comment