0

I have a java gui app that is supposed to handle an Exception. Here is the overall idea of my program: it is supposed to accept an input of integer number type. The input dialog should cause an Exception which should be caught and print the message "bad number". However, my problem is, how can I get repeating JPanelInput if user enters an empty string and/or bad format number. Also, if user chose CANCEL option, break out of JOptionPane.

String strIndex = this.showInputDialog(message, "Remove at index");
int index;

// while strIndex is empty && str is not type integer
while (strIndex.isEmpty()) {
      strIndex = this.showInputDialog(message, "Remove at index");
      try {
            if (strIndex.isEmpty()) {

            }
        } catch (NullPointerException np) {
            this.showErrorMessage("Empty field.");
        }


        try {
            index = Integer.parseInt(strIndex);
        } catch (NumberFormatException ne) {
            this.showErrorMessage("You need to enter a number.");
        }
}


    void showErrorMessage(String errorMessage) {
        JOptionPane.showMessageDialog(null, errorMessage, "Error Message", JOptionPane.ERROR_MESSAGE);
    }

    String showInputDialog(String message, String title) {
        return JOptionPane.showInputDialog(null, message, title, JOptionPane.QUESTION_MESSAGE);
    }

UPDATE:

String strIndex;
            int index;
            boolean isOpen = true;

            while (isOpen) {
                strIndex = view.displayInputDialog(message, "Remove at index");
                if (strIndex != null) {
                    try {
                        index = Integer.parseInt(strIndex);
                        isOpen = false;
                    } catch (NumberFormatException ne) {
                        view.displayErrorMessage("You need to enter a number.");
                    }
                } else {
                    isOpen = false;
                }
            }

1 Answers1

2

showInputDialog() returns null if the user chose to cancel. So here's the basic algorithm. I'll let you translate it to Java:

boolean continue = true
while (continue) {
    show input dialog and store result in inputString variable
    if (inputString != null) { // user didn't choose to cancel
        try {
            int input = parse inputString as int;
            continue = false; // something valid has been entered, so we stop asking
            do something with the input
        }
        catch (invalid number exception) {
            show error
        }
    }
    else { // user chose to cancel
        continue = false; // stop asking
    }
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255