I have to write a program that counts the lines in a file, the file is specified when starting the program:
java CountText textFile.txt
In the main method I use this code to get the filename entered in cmd:
if ( args.length > 0 ) {
String file = args[0];
}
Outside the main method I want to refer to this filename again:
public void Lines() throws Exception {
FileReader fr = new FileReader ( file );
The symbol can’t be found (which I don’t get because main method is public and static?). I feel like it’s a simple solution, but I can’t figure it out.
EDIT: Solved by Hovercraft Full Of Eels (also Travis). It is a scope issue which is solved by passing the String into the method via its parameter.
public class CountText {
public static void main ( String args[] ) throws Exception {
CountText count = new CountText();
if ( args.length > 0 ) {
String file = args[0];
count.Lines( file );
count.Words( file );
count.Characters( file );
}
}
public void Lines ( String file ) throws Exception {
FileReader fr = new FileReader ( file );
What you’re encountering here is a scope problem. Your variable is defined in the main function, so another function cannot access it. We say that the variable file is local to the main function.
One way to use the file variable inside your Lines method so that it accepts a string argument, which you can then pass to it. That would look like
So then you can call the method like so