如何在输入错误的java后重启程序

时间:2016-11-16 19:08:44

标签: java

如果输入了错误的电子邮件地址,我试图在某个时间点重新启动程序,这样用户就不会完全重启程序,以防他们拼写错误并且没有注意到。这就是我到目前为止所拥有的

public static void main(String[] args) {
    String grade = JOptionPane.showInputDialog(null, "Please Specify Your Grade");
    String First_name = JOptionPane.showInputDialog(null, "What is your First Name?");
    String Last_name = JOptionPane.showInputDialog(null, "What is your Last Name?");
    String message = "You are a " + grade + "\n"
            + "Your Name is " + First_name + " " + Last_name;
    JOptionPane.showMessageDialog (null, message);
    String email = JOptionPane.showInputDialog (null, "enter email");
        if (email.contains("@branfordschools.org")){                
            JOptionPane.showMessageDialog(null,"Password Accepted");
        } else {
            JOptionPane.showMessageDialog(null,"Password Incorrect, Program Closing");
            System.exit(0);
        }

看到java没有GOTO(在它引起问题之前会使用它,程序仅用于毕业演示)我将如何让它回到这里?

    String email = JOptionPane.showInputDialog (null, "enter email");
        if (email.contains("@branfordschools.org")){                
            JOptionPane.showMessageDialog(null,"Password Accepted");
        } else {
            JOptionPane.showMessageDialog(null,"Password Incorrect, Program Closing");
            System.exit(0);

2 个答案:

答案 0 :(得分:2)

这是一个简单的while循环,它将继续询问电子邮件,直到它包含“@ branfordschools.org”

    String email;
    Boolean validEmail = False;

    while(!validEmail)
    {
        //ask the user for the email
        email = JOptionPane.showInputDialog (null, "enter email");
        if (email.contains("@branfordschools.org")){                
            JOptionPane.showMessageDialog(null,"Password Accepted");
            validEmail = True;
        } else {
            JOptionPane.showMessageDialog(null,"Password Incorrect, Please Re-Enter Password");
        }
    }

答案 1 :(得分:0)

这应该有用;

 boolean validInput = false;
    while (!validInput) {
        String email = JOptionPane.showInputDialog(null, "enter email");
        if (email.contains("@branfordschools.org")) {
            validInput = true;
            JOptionPane.showMessageDialog(null, "Password Accepted");
        } else {
            JOptionPane.showMessageDialog(null, "Password Incorrect, Program Closing");
        }
    }