Reputation: 25
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);
}
}
Upvotes: 1
Views: 4575
Reputation: 211
try declaring
String name = "";
instead of
String name = null;
and then check if the string name is empty in the loop condition and in the if condition.
while (name.equals(""))
...
if (name.equals(""))
That's because the method showInputDialog returns an String, and the correct way to compare a String is using objectString.equals(anotherObjectString), you were comparing a String returned from showInputDialog with null, wich always return false.
Upvotes: 2
Reputation: 117597
This should solve the problem:
if(name == null || name.equals("")) {
JOptionPane.showMessageDialog(null, "No input.", "Error", JOptionPane.ERROR_MESSAGE);
name = null;
}
and regarding this question:
is there also a way to check if the input in the showInputDialog is a string?
showInputDialog()
returns String, even numbers, it reads them as String.
Upvotes: 3