I have this code that asks for a username and password. Just a simple JOptionPane. The program should ask an input and if the user did not write any input in the username, it should display an error message and displays the same, previous dialog box asking for a username. However, it does not work that way. Even though I do not input anything, it still proceed to the password dialog box. Please do check my logic, I might have been a bit confused; and is there also a way to check if the input in the showInputDialog is a string? somewhat like the NumberFormatException for integers? The Exception on catch method, does not work either. 🙂 Thanks in advance.
public class SwingExercise {
public static void main(String[] args) {
String name = null;
boolean input = true;
try {
while (input) {
while (name == null) {
name = JOptionPane.showInputDialog(null, "Enter username:");
if (name == null) {
JOptionPane.showMessageDialog(null, "No input.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
String pw = JOptionPane.showInputDialog(null, "Enter password:");
input = false;
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Invalid input.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
This should solve the problem:
and regarding this question:
showInputDialog()returns String, even numbers, it reads them as String.