Search code examples
javajoptionpane

How to print a message when the user selects something else except 1 or 2


I want an if statement that it will not let the user select something else and print an error message

while (!done) {

        String str1 = JOptionPane.showInputDialog("1:Student, 2:Graduate");
        if (str1.equals("1")) {
        //code
        } else if (str1.equals("2")) {
           //code`enter code here`
        } else if (str1.isEmpty()) {
            System.err.println("You have to choose between 1 and 2");
        }
}

Solution

  • You need to use with if and else if like this :

    String str1 = JOptionPane.showInputDialog("1:Student, 2:Graduate");
                    if (str1.equals("1")) {
                      System.out.println("Your chose 1");
            }
    
                    else if (str1.equals("2")) {
                        System.out.println("Your chose 2");
            }
    
                    else if (str1.isEmpty()) {
                        System.err.println("You have to choose between 1 and 2, your input is empty !");
            }
    
                    else {
                        System.err.println("You have to choose between 1 and 2");
                    }
                }
            }