I'm beginning a program that needs to read a file given in the command line. My first question is, if my command line looks like:
$java mysimulator 5 proc.txt
And I want to use proc.txt, which args is it? Right now I'm assuming that the class name is args[0] and so the filename is args[2].

My second question is about an error. At the beginning of my while loop, 'input' is getting an error saying that it is an unknown variable. However, it is defined as a Scanner above in the try catch block. Any ideas?

public class mysimulator {

    public static void main(String[] args) {
        //import file from command line
        try {
            Scanner input = new Scanner(new File(args[2]));
        } catch (FileNotFoundException ex) {
            System.out.println("No File Found!");


    }//end main

}//end mysimulator
6 Years
Discussion Span
Last Post by boos800

A quick and easy way, when debugging code, to see what is in the args[] array is to print out the Arrays.toString(args) value. It will show you the contents of args.

it is defined as a Scanner above in the try catch block

The variable is defined inside of {} and is not known/is out of scope outside of the {}.
Move the variable definition outside of the {} so it is a inside of same set of {} as any code wanting to use it.


thanks! lol its been a while since I've worked with java so I have forgotten trivial things like that.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.