我试图创建一个代码来读取密码,如果密码包含小写,则boolean应为false并继续使用其余代码。这是代码的一个片段:
import java.util.Scanner;
public class test
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
System.out.print("Enter a password that meets the following rules: \n\n");
System.out.print("8 characteres long\n");
System.out.print("Contains at least 1 lower letter\n");
System.out.print("Contains at least 1 upper letter\n");
System.out.print("Contains at least 1 numeric digit\n");
System.out.print("Contains 1 special character from "
+ "the set: !@#$%^&*\n");
System.out.print("Does not contain the word \"and\" "
+ "or the word \"end\"\n\n");
String password = stdIn.nextLine();
boolean hasLower;
hasLower = true;
for(int i = 0; (i<password.length()) && (!hasLower); i++){
if(Character.isLowerCase(password.charAt(i))){
hasLower = false;
}
}
System.out.println(hasLower);
} //end main
} // end class
答案 0 :(得分:4)
for循环中的逻辑是不正确的。
由于您将hasLower
变量初始化为true,因此for循环中的条件永远不会为true,因此for循环将永远不会运行:
(i<password.length()) && (!hasLower)
// !hasLower will not be true since the variable is initialised to true, whereas it should be initialised to false.
因此,要修复代码,请将hasLower
变量初始化为false,然后在找到小写字符时从循环中断。
hasLower = false;
for(int i = 0; i < password.length(); i++){
if(Character.isLowerCase(password.charAt(i))){
hasLower = true;
break; // Exits the last-entered loop.
}
}
答案 1 :(得分:1)
根据您的逻辑,它将跳过for循环。请改变第二个&amp;&amp; operator as(hasLower)。注意:不需要这些括号。
您可能会有以下内容
for (int i = 0; i < password.length() && hasLower; i++) {
if (Character.isLowerCase(password.charAt(i))) {
hasLower = false;
}
}