Java:简单循环

时间:2013-02-04 17:47:38

标签: java loops

这是一个没有任何循环的简单版本。如何让它像“密码错误”一样循环播放。再试一次。直到用户输入正确的密码而不是停止程序 (或在它停止之前给它们3次机会)?

    import java.util.Scanner;
public class helloworld2
{
    public static void main(String[] arg)
    {
        Scanner q = new Scanner(System.in);
        long Pass;
        boolean auth = true;

        System.out.println("Enter Password :");
        Pass = q.nextLong();

        if ( Pass != 1234 )
           {
           System.out.println("Wrong Password!");
           auth = false;
           }
        else
           {
           System.out.println("Password Confirmed.");
           auth = true;
           }

        if (auth) {
            ////blablabla
            }

        else
          {
            return;
          }                 
    }
}

1 个答案:

答案 0 :(得分:3)

public class helloworld2
{
    public static void main(String[] arg)
    {
        Scanner q = new Scanner(System.in);
        long Pass;
        boolean auth = true;
        boolean rightPassword = false;
        while(!rightPassword){//repeat until passwort is correct
          System.out.println("Enter Password :");
          Pass = q.nextLong();

          if ( Pass != 1234 )
          {
            System.out.println("Wrong Password!");
            auth = false;
          }
          else
          {
            rightPassword = true;//let the loop finish
            System.out.println("Password Confirmed.");
            auth = true;
          }
        }
        // Here do what you want to do
        //because here the user has entered a right password                 
    }
}