每次运行此程序时,我都会遇到无限循环,每次运行此程序时都会重复 else 语句“此密码不正确”
如果还有的话我还犯了什么其他错误?
public static void ValidChecker() {
Scanner scanner = new Scanner(System.in);
boolean correct = false;
while(correct == false)
System.out.println("please enter a password");
String pass = scanner.next();
for(int i = 0; i<pass.length(); i++) {
if(pass.charAt(i) == '!' && pass.length() > 8 ) {
System.out.println("this password is correct");
correct = true;
break;
}
else {
System.out.println("this password is incorrect");
break;
}
}
这是代码的 MRE,修复了您可以自己运行并尝试的问题
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean correct = false;
while(correct == false) {
System.out.println("please enter a password");
String pass = scanner.next();
for(int i = 0; i<pass.length(); i++) {
if(pass.charAt(i) == '!' && pass.length() > 8 ) {
System.out.println("this password is correct");
correct = true;
break;
}
else {
System.out.println("this password is incorrect");
break;
}
}
}
}
}
您的代码中的错误是缺少花括号。请记住,如果没有花括号,像
if
、while
等条件只会运行条件后的第一行。在你的情况下它会运行 while(correct == false) System.out.println("please enter a password");
。