DkgMarine
DkgMarine

Reputation: 27

variable might not been initialized from Scanner?

i declared the Scanner infile before the try-exception but for some reason it says varible might not been initialized?

Scanner infile;
        try 
        {
            infile = new Scanner(file);
        }
        catch(FileNotFoundException f)
        {
            System.out.println("Wrong File Path");
        }

        while (infile.hasNext())
        {
           System.out.print("Testing While loop");

Upvotes: 1

Views: 2053

Answers (3)

bobe
bobe

Reputation: 442

The best way to fix this would be to use Java's built in class error handling.

public static void main(String[] args) {
    Scanner infile;
    try {
        infile = new Scanner(new File("filename.txt"));
    } catch (FileNotFoundException f) {
        System.out.println("Wrong File Path");
    }

    while (infile.hasNext()) {
        System.out.print("Testing While loop");
    }
}

This code will not compile because there is a possibility that the file will not be found and the error is not handled, but if you add throws FileNotFoundException to the main function declaration, the exception will be handled by the main function and won't cause any problems.

public static void main(String[] args) throws FileNotFoundException{
    Scanner infile;
    infile = new Scanner(new File("filename.txt"));
    
    while (infile.hasNext()) {
        System.out.print("Testing While loop");
    }
}

Sorry if my explanation isn't very good, I'm only just starting out with Java myself.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074168

Consider what happens if an exception is thrown in the new Scanner constructor call. The constructor never completes, and so new Scanner(file) doesn't result in a value; what then for infile?

To correct it, move your while loop into the try block:

Scanner infile;
try 
{
    infile = new Scanner(file);

    while (infile.hasNext())
    {
       System.out.print("Testing While loop");
    }
}
catch(FileNotFoundException f)
{
    System.out.println("Wrong File Path");
}

The purpose of exception handling, after all, is to get it out of the way of your main logic.

Upvotes: 1

Tavo
Tavo

Reputation: 3151

Imagine the situation where infile = new Scanner(file); throws an Exception. At the point of while (infile.hasNext()), infile would not have been initialised.

You can solve this problem by just changing Scanner infile; for Scanner infile = null;. But be aware that infile can still be null at this point if the said exception is thrown. You should put that part of the code inside the try block.

Upvotes: 0

Related Questions