[英]Using Java Loops To Return To Another Portion of The Program?
我一直在自學Java,並且在循環方面受困。 我知道您可以利用“ while”循環來幫助將Java程序帶回到代碼的特定部分……但是我不確定如何實現。
這是我要尋找的:在代碼的有效或無效結果完成后,我希望它返回到提示用戶輸入密碼的代碼部分。
這是下面我的代碼的副本...任何幫助將不勝感激!
import java.util.Scanner;
public class Password {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Prompts the user to enter a password, and stores password in the string "passwordIn."
System.out.print("Please enter a password to determine if it is valid or not: ");
String passwordIn = input.nextLine();
//Established various boolean checks to be passed in order for code to evaluate each character.
boolean lengthCheck = false;
boolean upperCheck = false;
boolean lowerCheck = false;
boolean digitCheck = false;
boolean specialCheck = false;
boolean check = false;
//The loop will initiate the testing of the string.
for(int i = 0; i < passwordIn.length(); i++) {
//Character pw represents the index!
char pw = passwordIn.charAt(i);
//This verifies that the password meets the length (at least 8 characters) requirement.
if (passwordIn.length() >= 8) {
lengthCheck = true;
}
//This verifies that there is at least one uppercase letter in the password.
if(Character.isUpperCase(pw)) {
upperCheck = true;
}
//This verifies that there is at least one lowercase letter in the password.
if(Character.isLowerCase(pw)) {
lowerCheck = true;
}
//This verifies that there is at least one digit in the password.
if(Character.isDigit(pw)) {
digitCheck = true;
}
//This verifies that there is at least one character that is not a letter or a number within the password.
if(!Character.isLetter(pw) && !Character.isDigit(pw)) {
specialCheck = true;
}
}
//Verifies the results of the loop to ensure that all checks are true.
if(upperCheck == true && lowerCheck == true && digitCheck == true && lengthCheck == true && specialCheck == true) {
check = true;
}
// Uses boolean to determine if password is valid.
if (check == true) {
System.out.print("\nThe password you entered was: " + passwordIn);
System.out.print("\nVerdict: " + "\t" + "Valid");
}
else {
System.out.print("\nThe password you entered was: " + passwordIn);
System.out.print("\nVerdict: " + "\t" + "Invalid");
}
}
}
對於這樣的事情,通常需要一段while
測試布爾值
boolean check = false;
//The loop will initiate the testing of the string.
while(!check) {
但是,您將必須移動從用戶讀取密碼的語句,以執行任何有用的操作。
boolean check = false;
//The loop will initiate the testing of the string.
while(!check) {
//Prompts the user to enter a password, and stores password in the string "passwordIn."
System.out.print("Please enter a password to determine if it is valid or not: ");
String passwordIn = input.nextLine();
// ... testing...
}
您可以如下使用do-while
循環。
do{
// logic to validate
} while(condition); // Your break condition here
這將執行一次邏輯,然后檢查中斷條件。 如果為true
則它將再次執行邏輯。 這一直持續到遇到中斷條件或程序終止為止。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.