0

I'm using a try/catch statement to force valid user input to assign to a variable. However, when I try to use this variable outside the try/catch statement, it tells me that my variable has not been initialized. Using Java... Link to picture of error

public static int getChoice() 
{
    //Variables
    int choice;

    do {

        try {
        System.out.println("Press 1 then [Enter] for imperial measurements: ");
        System.out.println("Press 2 then [Enter] for metric measurements: ");
        choice=console.nextInt();
        }

        catch (InputMismatchException inputMismatchException) { //Force valid input of integer

            System.err.println("\nInvalid entry.");
            System.out.println("Press 1 then [Enter] for imperial measurements: ");
            System.out.println("Press 2 then [Enter] for metric measurements: ");
            console.nextLine(); //Flush line buffer
        }


    } while (choice<1||choice>2); //Forces input of either 1 or 2

    return choice;
}
  • Which language are you using? Add the language name with a tag please. – user202729 Mar 06 '18 at 02:02
  • 1
    `it tells me that my variable has not been initialized` Why not include the actual error message. This will make it much easier to find the duplicate. – John3136 Mar 06 '18 at 02:10
  • 2
    Possible duplicate of [Variable might not have been initialized error](https://stackoverflow.com/questions/2448843/variable-might-not-have-been-initialized-error) – John3136 Mar 06 '18 at 02:11
  • Because it indeed may not be initialized (if it throws a `InputMismatchException`). – user202729 Mar 06 '18 at 02:13

2 Answers2

0

You need to either define a value when you declare choice, like using int choice = 0;, or add a line inside the catch clause, choice = 0;.

kshetline
  • 12,547
  • 4
  • 37
  • 73
0

Explanation

The cause of this error is obvious. There is a branch in your code where you could call choice without assigning any value to it. This happens when the try block is aborted before something is assigned to choice.

In this case this would be when an InputMismatchException occurs, the try block is then aborted and the control flow continues with the catch block. After the catch block choice is accessed though it was not initialized.

int choice; // Declaration without initialization
do {
    try {
        // ...
        choice = console.nextInt(); // Exception could be thrown
    } catch (InputMismatchException inputMismatchException) {
        // ...
        // Code then continues here, without choice being initialized
    }
} while (choice < 1 || choice > 2); // Access of unassigned variable

Solutions

You have several options for fixing this. You must make sure that there can not be a branch that accesses choice unassigned. Therefore, you could assign it with a default value before entering the loop:

int choice = -1; // Default value

Of course you would need to handle this special case then.

Another possibility is to assign it in the catch block too

} catch ( ... ) {
    choice = -1; // Some value indicating an error
}

You could make sure that a dangerous branch never reaches choice, for example by aborting the code in some way:

} catch ( ... ) {
    throw new IllegalStateException(); // Abort by throwing a non-catched exception
}

You could protect the access to choice with some kind of guard variable:

boolean wasError = false;
int choice;
do {
    try {
        // ...
    } catch (InputMismatchException inputMismatchException) {
        // ...
        wasError = true; // Set the guard
    }

    // Check the guard
    if (wasError) {
        // Something went wrong, abort the loop
        break;
    }
} while (choice < 1 || choice > 2);
Zabuzard
  • 25,064
  • 8
  • 58
  • 82