Search code examples
javawhile-loopjoptionpane

Input dialog loop end early


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?


Solution

  • 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:");
    }