我正在製作一個簡單的程序,用於在啓動程序之前詢問密碼。當我的用戶輸入錯誤的密碼時,他們會收到「拒絕訪問」警告。我使用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語句被觸發,我怎麼能完全重新啓動我的程序,而無需再次手動點擊運行按鈕?
你有沒有聽說過的循環(對於,而等)?只需循環代碼,直到輸入正確,然後繼續程序(可能會嘗試進行最大嘗試次數)。 – dunni
我忘了說我是編程新手。我將相應地編輯我的問題。 – Jake
或給他們一個輸入密碼或退出選項,但作爲@dunni說while(!Verified){GetPassword()}基本上是要走的路。 –