I'm attempting to read the file.txt into java line by line and then when a line is "foo" I set the line after it to be "lineAfterFoo" then output that to the user.
My Java Code....
public void main(String[] args) throws IOException {
try {
FileReader someFile = new FileReader("file.txt");
BufferedReader input = new BufferedReader(someFile);
int i = 0;
String[] line;
line = new String[10];
line[i] = input.readLine();
while(line[i] != null) {
line[i] = input.readLine();
if (line[i] == "foo") {
i = i + 1;
line[i] = "lineAfterFoo";
}
i = i + 1;
}
for (int number = 1; number < i; number++) {
System.out.println(line[number]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
File.txt
1
2
3
foo
HopeFullyThisWillChange
5
6
7
8
9
10
The Error...
java.lang.NoSuchMethodError: main
Exception in thread "main"
Thanks for any help!
The main
method must be static
:
public static void main(String[] args) throws IOException {
// snip...
}
The loop only runs once because, after the first pass through the while
body, i
will be equal to 1
. At that point line[1]
is null, because you haven't read anything into it. Here's the typical idiom used instead (note the changes in variable names):
int i = 0;
String line = null;
String[] lines = new String[10];
// read the next line and immediately check to see if it's null
// also make sure that i doesn't go out of range
while ((line = input.readLine()) != null
&& i < lines.length) {
lines[i] = line;
// Use .equals() (not ==) when comparing strings!
if ("foo".equals(line)) {
i++; // shorter form of i=i+1
lines[i] = "lineAfterFoo";
}
i++;
}