Reputation: 139
When the user enters nothing in an input dialog box it ends the loop below. I've debugged the code and name is indeed "" when the user enters nothing.
while(name == "" || name == null){
name = JOptionPane.showInputDialog("Enter your name:");
}
Also, When the window containing the input dialog is closed or cancelled, the program doesn't exit the loop.
Can anyone provide some insight for me?
Upvotes: 0
Views: 506
Reputation: 139
The window closing not causing the program to exit the loop is because I needed to add a default close operation by calling JFrame's setDefaultCloseOperation with the parameter JFrame.EXIT_ON_CLOSE. This terminates the JFrame and prevents it from running in the background after the window is closed.
Upvotes: 0
Reputation: 124235
Don't compare strings with name == ""
. Use "".equals(name)
or in your case even name.isEmpty()
(available since Java 6).
==
is used to compare references, not value of objects. More info here.
Change your code to:
while(name == null || name.isEmpty()){
name = JOptionPane.showInputDialog("Enter you're name:");
}
Upvotes: 2
Reputation: 38300
Stop comparing strings and start using the Apache Commons Lang StringUtils class. It handles nulls nicely and is well tested. You will want to use StringUtils.isBlamk(name)
or StringUtils.isEmpty(name)
Upvotes: 0
Reputation: 11310
There is a big difference using "==" oder equals. Try also to use equalsIgnoreCase() to be sure
while(name == null || name.equalsIgnoreCase("")){
name = JOptionPane.showInputDialog("Enter you're name:");
}
Upvotes: 0