2013-02-04 68 views
0

這是一個沒有任何循環的簡單版本。我怎樣才能讓它循環像「錯誤的密碼,再試一次。」直到用戶輸入正確的密碼而不是停止程序 (或者在它停止之前給他們3次機會)?Java:Simple Loop

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; 
      }     
    } 
} 
+2

你需要['do'-'while'環路(http://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html)。 –

+1

變量名不能大寫('Pass')這是用於類名的。 –

+1

只是一個簡單的說明:閱讀Java Sun約定=) – JMarques

回答

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     
    } 
}