File I/O Modify Text Problem
hello, i would really apreciate any help on this one.. i have just started file i/o in java and already the homework is bugging me.
I am to write a program that reformats java source code from the next-line brace style to the end-of-line brace style. for example the following code :
Code Java:
public class Test
{
public static void main(String[] args)
{
// some statements
}
}
would be reformatted to :
Code Java:
public class Test{
public static void main(String[] args){
// some statements
}
}
my attempted code so far is below.. i don't know if i can use concat() in this instance and if i am even doing anything right... please help.. thanks.
Code Java:
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
File file = new File("C:\\JackTest\\test.txt");
format(file);
}
public static void format(File f) throws Exception {
Scanner input = new Scanner(f);
String[] lines = new String[7];
while (input.hasNext()) {
for (int i = 0; i < 7; i++) {
lines[i] = input.nextLine();
if (lines[i].startsWith("{")) {
lines[i-1].concat("{");
// i am stuck here..
}
}
}
}
}
Re: File I/O Modify Text Problem
In Java, strings are immutable (i.e. they can't be changed). You must re-assign the array the return value which holds the new string. Also, fyi Java defines the "plus" operator between strings as concatenating them.
Code Java:
lines[i-1] += "{"; // short-handed "add then assign" also works
Re: File I/O Modify Text Problem
I would of thought that a reasonable approach to this would be to locate a \n followed by any number of whitespace characters followed by { and replace with just {
Chris