2015-04-22 50 views
1

我正在製作一個簡單的程序,用於在啓動程序之前詢問密碼。當我的用戶輸入錯誤的密碼時,他們會收到「拒絕訪問」警告。我使用If/Else語句來實現這一點。我想要做的就是重新運行我的程序,如果他們輸入了錯誤的密碼,他們不能再次鍵入控制檯,如果他們錯了。Java:如何在觸發「其他」語句時自動重新啓動控制檯程序

這是我的工作區:

import java.util.Scanner; 

public class PasswordProtected { 
    public static void main (String args[]){ 
     Scanner Password = new Scanner (System.in); 
     String mainpassword, userInput; 
     mainpassword = ("Jacob"); 
     System.out.println("Please enter the password to continue."); 
     userInput = Password.nextLine(); 
     System.out.println("Verifying Password"); 
     if (userInput.equals(mainpassword)){ 
      System.out.println("Access Granted"); 
      System.out.println("Welcome!"); 
     }else{ 
      System.out.println("Access Denied"); 
     } 
    } 

} 

我也知道,我可以複製一些這樣的事了一遍又一遍,但是,它是浪費空間是不是無限的。

System.out.println("Please enter the password to continue."); 
      userInput = Password.nextLine(); 
      System.out.println("Verifying Password"); 
      if (userInput.equals(mainpassword)){ 
       System.out.println("Access Granted"); 
       System.out.println("Welcome!"); 
      }else{ 
       System.out.println("Access Denied"); 
      } 
     } 

請注意,我是新的節目,並可能需要一點額外的幫助。

如果Else語句被觸發,我怎麼能完全重新啓動我的程序,而無需再次手動點擊運行按鈕?

+4

你有沒有聽說過的循環(對於,而等)?只需循環代碼,直到輸入正確,然後繼續程序(可能會嘗試進行最大嘗試次數)。 – dunni

+0

我忘了說我是編程新手。我將相應地編輯我的問題。 – Jake

+0

或給他們一個輸入密碼或退出選項,但作爲@dunni說while(!Verified){GetPassword()}基本上是要走的路。 –

回答

2

您不需要重新啓動程序。如果密碼不正確,請使用循環再次詢問密碼。例如,在半僞代碼while聲明:

userInput = input.nextLine(); 
while (!userInput.equals(mainpassword)){ 
    userInput = input.nextLine(); 
} 
+0

我已經嘗試過所有人的迴應,但是(也許不正確),你的工作。 – Jake

+0

我意識到我無法讓我的用戶在此之後輸入任何其他信息。爲什麼?每當我嘗試按下輸入(對於新的信息),就會彈出關於再次創建帳戶的相同代碼。 – Jake

+0

不知道,因爲我看不到你的代碼。 – copeg

1

嘗試while(true)

String mainpassword = ("Jacob"); 
String userInput = null; 
Scanner Password = new Scanner (System.in); 

while(true) { 
    userInput = Password.nextLine(); 

    if (userInput.equals(mainpassword)){ 
     break; 
    } else { 
     System.out.println("Access Denied"); 
    } 
} 

System.out.println("Access Granted"); 
System.out.println("Welcome!"); 
+0

這個。但更好的選擇是分析它們的輸入是空白的,然後做,而不是做... while(userInputWasNotBlank)...然後指示他們,如果他們想要退出他們只需按下輸入,而不輸入任何其他內容...請參閱https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html – Bane

1

如果你還是覺得重新啓動任何Java程序,那麼main()方法可以從其他地方調用在你的代碼中。你可以調用這個方法,傳入任何必要的String參數。如果你想在一個新的進程重新啓動應用程序使用一個線程來做到這一點,如下

Thread t = new Thread() { 
    public void run() {    
     String[] args = { }; 
     PasswordProtected.main(args);  
    } 
}; 
t.start(); 

,您可以使用

Runtime.getRuntime().exec(...); 
相關問題