Ok, I have this code that asks an input for a username and a password. I used JOptionPane
. What I want with the program is to display an error message if the the input on the username field has a number, and goes back to the previous dialog box asking for the username again. I have this while loop yet it does not function the way it should. Please do help. The program does not show the error message on my catch
method and neither does it loop for the dialog box to display.
public class SwingExercise {
public static void main(String[] args) {
String name = "";
String pw = "";
boolean input = true;
boolean hasDigit = false;
while (input) {
try {
while (name.equals("")) {
name = JOptionPane.showInputDialog(null, "Enter username:");
if (name.equals("")) {
JOptionPane.showMessageDialog(
null, "No input.", "Error", JOptionPane.ERROR_MESSAGE);
name = "";
}
while (hasDigit) {
for (int i = 0; i < name.length(); i++) {
if (Character.isDigit(name.charAt(i))) {
throw new InputMismatchException();
}
}
hasDigit = false;
}
}
input = false;
while (pw.equals("")) {
pw = JOptionPane.showInputDialog(null, "Enter password:");
if (pw.equals("")) {
JOptionPane.showMessageDialog(
null, "No input.", "Error", JOptionPane.ERROR_MESSAGE);
pw = "";
}
}
} catch (NullPointerException e) {
System.exit(0);
} catch (InputMismatchException e) {
JOptionPane.showMessageDialog(
null, "Invalid input.", "Error", JOptionPane.INFORMATION_MESSAGE);
}
}
}
Please do mention any comments regarding the other lines in my code and if there are any unnecessary lines. Thank you in advance :)
One problem is that the value of hasDigit will always remain false. You probably will want to define hasDigit as true initially.
boolean hasDigit = true;