Search code examples
javaloopsjoptionpane

Boolean loop combined with JOptionPane Java


I would love to share my code. But in my university the code gets tested for "cheating".

But here is my code in simplier form.

public static String readin() {
    boolean error = false;
    do {
        string stringin;
        stringin = JOptionPane.showInputDialog(null, "Please enter a number");
        switch (stringin.length()) {
            case 0:
                JOptionPane.showMessageDialog(null, "Error Please repeat");
                error = true;

            case 1:
                return stringin;
        }
        return null;
    } while (error == true);
}

This Code is really in it's simpliest form. I know that for this case it would be smarter to set the while to JOptionPane is empty or something. Since in my code are like 12 different error cases. I want to use the boolean. Please: the return null will never occur in the real code.

But the real problem I have: It works perfectly fine besides: if he repeats the loop he doesn't give me the chance to type a new stringin in. How can i do this?

Also I am sorry for my faults in english.

EDIT: All your helps fixed my problems! Thank you very much! I love this forum!


Solution

  • Try with break before case 1 (@Tuxxy_Thang) and remove return null; before while (error); and put after.

    public static String readin(){
        boolean error=false;
        do{ 
            string stringin;
            stringin=JOptionPane.showInputDialog(null,"Please enter a number");
            switch (stringin.length()){
                case 0: JOptionPane.showMessageDialog(null, "Error Please repeat");
                    error=true;
                    break;
                case 1: return stringin;
            } 
        } while (error);
        return null;
    }