0

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?

Al G Johnston
  • 129
  • 2
  • 10

5 Answers5

2

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:");
}
Community
  • 1
  • 1
Pshemo
  • 122,468
  • 25
  • 185
  • 269
1

Never use == to compare Strings in Java.

Use the method equals(String).

See the following link

Michael
  • 1,209
  • 2
  • 12
  • 25
0

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:");
    }
Festus Tamakloe
  • 11,231
  • 9
  • 53
  • 65
0

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)

DwB
  • 37,124
  • 11
  • 56
  • 82
0

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.

Al G Johnston
  • 129
  • 2
  • 10