我一直在自学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");
}
}
}
答案 0 :(得分:0)
对于类似的东西,通常用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...
}
答案 1 :(得分:0)
您可以使用do-while
循环,如下所示。
do{
// logic to validate
} while(condition); // Your break condition here
这将执行逻辑一次,然后检查中断条件。如果它是true
那么它将再次执行逻辑。这一直持续到遇到中断状态或程序终止。