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!");
            return;
        }

       while(input.hasNext()){
           //...
       }
        

    }//end main

}//end mysimulator

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.