I am trying to make a program that reverses the text lines in a file. I am still learning java and I am new to this. My program was erroring because I made a variable inside a loop and tried to access it outside. I tried adding the preffix "public" before declaring the string variable but when I try to compile it it points to the "public" and says illegal start of expression. Can someone please tell me why this is erroring and or how to fix it.
import java.io.*;
import java.util.*;
public class FileReverser
{
public static void main(String[] args)
throws FileNotFoundException
{
Scanner console = new Scanner(System.in);
System.out.print("File to Reverse: ");
String inputFileName = console.next();
System.out.print("Output File: ");
String outputFileName = console.next();
FileReader reader = new FileReader(inputFileName);
Scanner in = new Scanner(reader);
PrintWriter out = new PrintWriter(outputFileName);
int number = 0;
while (in.hasNextLine())
{
String line = in.nextLine();
public String[] lines;
lines[number] = line;
number++;
}
int subtract = 0;
for (int i;i>lines.length;i++)
{
out.println(lines[(lines.length-subtract)]);
subtract++;
}
out.close();
}
}
Problems:
lines
with the public
modifier, which is only for instance/static variables, not local variables.lines
lines
outside its scope (which is currently the while
loop)You're trying to use i
without initializing it, here:
for (int i;i>lines.length;i++)
if
condition is the wrong way round; you would want to continue while i
is less than lines.length
subtract
is initially 0, so accessing lines[lines.length - subtract]
will throw an exception (as it's outside the bounds of the array)You can fix these with the following code:
// See note later
String[] lines = new String[1000];
while (in.hasNextLine()) {
String line = in.nextLine();
lines[number] = line;
number++;
}
// Get rid of subtract entirely... and only start off at "number"
// rather than lines.length, as there'll be a bunch of null elements
for (int i = number - 1; i >= 0; i--) {
out.println(lines[i]);
}
Now that will work for up to 1000 lines - but it's a pain to have that limitation. It would be better just to use a List<String>
:
List<String> lines = new ArrayList<String>();
while (in.hasNextLine()) {
lines.add(in.nextLine());
}
Then you'd need to use size()
instead of length
, and use get
instead of the array indexer to access the values - but it would be cleaner code IMO.
See more on this question at Stackoverflow