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;
}
}