user1428565
user1428565

Reputation: 23

Java Exception Handling Variable Not Initialised

I am trying to catch an exception where text is inserted and the program has to parseInt. Upon compile it is saying the the variable num might not have been initialised. (Line 31) I cannot work out why it would be doing this.

Code follows. Thanks in advance.

// Java packages
import javax.swing.JOptionPane; 
// program uses JOptionPane

class Help2Gui {
    public static void main(String args[]) {

        // variable declaration
        String choice;
        int num;

        // read in first number from user as a string
        choice =
            JOptionPane
                .showInputDialog("Help on: \n \t 1. class \n \t 2. object \n \t 3. method \n \t 4. variable \n \t 5. constructor \n \t 6. Quit \n Enter a number from the list above.");

        if (choice == null) {
            System.exit(0);
        }

        do { // begin a loop to display initial choice, repeating until 6 is
             // entered

            // convert numbers from type String to type int
            try {
                num = Integer.parseInt(choice);
            }

            catch (NumberFormatException nfe) {

            }

            switch (num) { // display result for each item entered by user
            case 1:
                JOptionPane.showMessageDialog(null,
                    "\n A class is a definition of an object.",
                    "Java Help System", JOptionPane.PLAIN_MESSAGE);
                break;

            case 2:
                JOptionPane
                    .showMessageDialog(
                        null,
                        "The switch: \n \n switch (expression) { \n case constant: \n statement sequence \n break \n // ... \n } ; ",
                        "Java Help System", JOptionPane.QUESTION_MESSAGE);
                break;

            case 3:
                JOptionPane
                    .showMessageDialog(
                        null,
                        "The for: \n \n for(init; condition; iteration) \n statement;",
                        "Java Help System", JOptionPane.INFORMATION_MESSAGE);
                break;

            case 4:
                JOptionPane.showMessageDialog(null,
                    "The while: \n \n while(condition) statement;",
                    "Java Help System", JOptionPane.WARNING_MESSAGE);
                break;

            case 5:
                JOptionPane
                    .showMessageDialog(
                        null,
                        "The do-while: \n \n do { \n statement; \n } while (condition);",
                        "Java Help System", JOptionPane.ERROR_MESSAGE);
                break;

            case 6:
                System.exit(0);
                break;

            default:
                JOptionPane.showMessageDialog(null,
                    "Enter a number from 1 to 5 or 6 to Quit",
                    "Java Help System", JOptionPane.ERROR_MESSAGE);
            }

            // read in first number from user as a string
            choice =
                JOptionPane
                    .showInputDialog("Help on: \n \t 1. if \n \t 2. switch \n \t 3. for \n \t 4. while \n \t 5. do-while \n \t 6. Quit \n Enter a number from the list above.");
            try {
                // attempt to convert the String to an int
                num = Integer.parseInt(choice);

            }
            catch (NumberFormatException nfe) {
                JOptionPane.showMessageDialog(null,
                    "Enter a number from 1 to 5 or 6 to Quit",
                    "Java Help System", JOptionPane.ERROR_MESSAGE);
            }
            // convert numbers from type String to type int

        }
        while (num != 6); // end of do-while loop.

        System.exit(0); // terminate application with window

    } // end method main

} // end class Help2Gui

Upvotes: 2

Views: 2437

Answers (7)

tgoossens
tgoossens

Reputation: 9856

replace by

 int num = 0;

this should do the trick

Upvotes: 0

Thihara
Thihara

Reputation: 6969

It's because you variable num is not initialized with any value if an exception is thrown. In that case all operations will fail because num won't have a value. If num was a variable outside of the method scope then it will get a default value. but variables declared inside methods will not receive any default value. You can assign a separate value like -1 for num when the exception is thrown or initialize it when you declare it. Basically you have a lot fo options on how to handle this.

Upvotes: 0

Aneesh Narayanan
Aneesh Narayanan

Reputation: 3434

initialize the num before the try block. If any exception is thrown from the type conversion, then the num will not be initialized. And also for a good programming practise initialize all the variable before get using it, if possible.

Upvotes: 0

ratchet freak
ratchet freak

Reputation: 48216

put a num=0; in the catch as the implicit default

Upvotes: 0

npinti
npinti

Reputation: 52185

The problem is that you are doing this: int num;. You are not assigning any value to it. In your do while loop you are populating the value, but this could throw an exception which would cause your variable to still be non initialized when it reaches the switch statement. I would recommend you populate you num variable with some initial, fallback value and then update the value within the loop.

As an another recommendation, I would recommend you do not swallow exceptions and within the catch section you provide some value for the num variable should an exception be caught.

Upvotes: 0

amit
amit

Reputation: 178491

If the exception is thrown and caught, the variable num is not initialized by

num = Integer.parseInt( choice );

and then there will be a problem with:

switch (num) { //what is num in here?

To solve this - you can give a default value for these cases (in the exception handler, or prior to the try block, so the assignment to num will override the default value), or terminate the method when the exception is thrown.
Simplest solution IMHO (though it not always fits) will be to initialize num while declaring it, something like:

int num = MY_DEFAULT_VALUE;

Upvotes: 4

bmargulies
bmargulies

Reputation: 100133

If parseInt throws an exception, num is not initialized. Initialize it to something before the catch block.

Upvotes: 0

Related Questions