Search code examples
javajoptionpanenumberformatexception

Java NumberFormatException


@MadProgrammer, I have used the NumberFormatException to capture blanks or characters and throw back a warning message. It was successful for the main page but for the option, "add t", instead of display each t-shirt color it loops around the first color, blue. I have also tried 'while' loop statement but it causes the program to stop. If it worked for the first part, display_menu(), I don't understand why it doesn't work for "add_t".

import javax.swing.JOptionPane;

public class OnlineStore {

    String[] ColorType = { "blue", "green", "black" };
    final int COLOURS = 3; // t choices
    int[] Color = new int[COLOURS];
    int sum;

    public int display_menu(){ // Not the main program but the main menu.
        String input = null;
        boolean test = true;
        while (test == true) {
            try {
                input = JOptionPane.showInputDialog("Welcome!" + "\n\n1. Add t order\n2. Edit t order\n3. View current order\n4. Checkout" + "\n\nPlease enter your choice: ");
                return Integer.parseInt(input);
            } catch (NumberFormatException nfe) {
                JOptionPane.showMessageDialog(null, "Input must be a number.");
            }
        }
        return Integer.parseInt(input);
    }

    public OnlineStore(){ // Switch-case program
        boolean exit = false;
        do {
            switch (display_menu()) {
            case 1:
                add_t();
                break;
            case 2:
                exit = true;
                break;
            default: // If an error is encountered.
                JOptionPane.showMessageDialog(null, "Oh dear! Error!");
                break;
            }
        } while (!exit);
    }

    public final int add_t() {
        for (int index = 0; index < ColorType.length; index++) {
            boolean test = true;
            while (test == true) {
                try {
                    String orderItems = JOptionPane.showInputDialog("Please enter your t order for " + ColorType[index]);
                    int items = Integer.parseInt(orderItems);
                    Color[index] = items;
                } catch (NumberFormatException nfe) {
                    JOptionPane.showMessageDialog(null, "Input must be a number.");
                }
            }
        }
        sum = Color[0] + Color[1] + Color[2];
        JOptionPane.showMessageDialog(null, "Your total order is " + sum);
        return Color.length;
    }

    public static void main(String[] args){ // Main program
        new OnlineStore(); // Call out the program.
    }
}

Solution

  • Let's have a quick look at add_t...

    public final int add_t() {
        for (int index = 0; index < ColorType.length; index++) {
            boolean test = true;
            while (test == true) {
                try {
                    String orderItems = JOptionPane.showInputDialog("Please enter your t order for " + ColorType[index]);
                    int items = Integer.parseInt(orderItems);
                    Color[index] = items;
                } catch (NumberFormatException nfe) {
                    JOptionPane.showMessageDialog(null, "Input must be a number.");
                }
            }
        }
        sum = Color[0] + Color[1] + Color[2];
        JOptionPane.showMessageDialog(null, "Your total order is " + sum);
        return Color.length;
    }
    

    First, you have a for-loop so you can prompt for each color type, not unreasonable, next you have while (test == true), now, having a quick loop inside the loop, there's no exit condition, no where do you set test to false so the loop can exit...opps, infinite loop.

    The reason it works in your previous attempt is, if no error is generated by Integer.parseInt, the value is automatically returned

    return Integer.parseInt(input);
    

    Now, I'm old school, I like one entry point and one exit from a method, it prevents mistakes or misunderstandings like this one.

    Instead, since this seems like something you might do a lot, I'd write a simple "prompt for a integer" method, something like...

    public Integer promptForInt(String prompt) {
        Integer value = null;
        boolean exit = false;
    
        do {
            String input = JOptionPane.showInputDialog(prompt);
            if (input != null) {
                try {
                    value = Integer.parseInt(input);
                } catch (NumberFormatException exp) {
                    JOptionPane.showMessageDialog(null, "Input must be a number.");
                }
            } else {
                exit = true;
            }
        } while (value == null && !exit);
    
        return value;
    }
    

    Now, all this does is asks the user for int value. It will keep looping until the user either enters a valid int value or presses cancel. The method will either return a int (Integer to be exact) or a null. The null indicating that the user pressed the cancel button

    Now, you can simply use

    public int display_menu() // Not the main program but the main menu.
    {
        Integer value = promptForInt("Welcome!" + "\n\n1. Add t order\n2. Edit t order\n3. View current order\n4. Checkout" + "\n\nPlease enter your choice: ");
        return value != null ? value : 4;
    }
    

    and

    public final int add_t() {
        boolean canceled = false;
        for (int index = 0; index < ColorType.length; index++) {
    
            Integer value = promptForInt("Please enter your t order for " + ColorType[index]);
            if (value != null) {
                Color[index] = value;
            } else {
                canceled = true;
                break;
            }
        }
        if (!canceled) {
            sum = Color[0] + Color[1] + Color[2];
            JOptionPane.showMessageDialog(null, "Your total order is " + sum);
        }
        return canceled ? -1 : Color.length;
    }
    

    to ask for int values from the user