Java密码检查器布尔返回值始终为false问题排查求助
问题分析与修复方案
首先,你的代码总是返回false的核心原因不是flag初始化的问题,而是在判断大小写和数字的辅助方法里犯了一个关键错误——你传入Character.isUpperCase()等方法的参数是循环索引i,而不是字符串中对应的字符!另外hasNoSpaces方法的写法也有冗余,我们一步步来修复:
1. 修复大小写与数字判断的核心错误
看你的atLeastOneUpper、atLeastOneLower、atLeastOneDigit方法,比如:
private static boolean atLeastOneUpper(String pwd) { boolean flag = false; for(int i = 0; i<pwd.length(); i++) { // 错误:这里传入的是索引i,不是字符pwd.charAt(i) if(Character.isUpperCase(i)) flag = true; } return flag; }
Character.isUpperCase(int)需要的是字符的Unicode码点,而你传入的是循环的索引值(比如0、1、2...),这些数字对应的字符都不是大写字母,所以这个方法永远会返回false!同理另外两个方法也一样。
正确的写法应该是获取字符串中对应索引的字符,而且找到符合条件的字符后可以直接返回,不用继续循环(既修复错误又提升效率):
private static boolean atLeastOneUpper(String pwd) { for(int i = 0; i<pwd.length(); i++) { if(Character.isUpperCase(pwd.charAt(i))) { return true; } } // 循环结束没找到,返回false return false; }
同样修改另外两个方法:
atLeastOneLower:把Character.isLowerCase(i)改成Character.isLowerCase(pwd.charAt(i))atLeastOneDigit:把Character.isDigit(i)改成Character.isDigit(pwd.charAt(i))
2. 优化hasNoSpaces方法
你的hasNoSpaces方法用循环遍历每个字符,但每次都判断整个字符串是否包含空格,完全没必要。可以简化成两种更高效的写法:
写法一:直接利用String的contains方法(最简洁)
private static boolean hasNoSpaces(String pwd) { return !pwd.contains(" "); }
写法二:循环检查每个字符(找到空格立即返回)
private static boolean hasNoSpaces(String pwd) { for(int i = 0; i<pwd.length(); i++) { if(pwd.charAt(i) == ' ') { // 找到空格,直接返回false return false; } } // 循环结束没找到空格,返回true return true; }
两种写法都能正确工作,而且都不需要flag变量。
3. 其他可优化的点
你的isLongEnough方法可以简化成一行,更简洁易读:
private static boolean isLongEnough(String pwd) { return pwd.length() >= 6; }
修复后的完整代码
把上面的修改整合后,代码应该能正常工作了:
public static boolean isLevel1(String pwd) { int howMany = 0; if(isLongEnough(pwd) && hasNoSpaces(pwd)) { if(atLeastOneUpper(pwd)) howMany++; if(atLeastOneLower(pwd)) howMany++; if(atLeastOneDigit(pwd)) howMany++; if(howMany >= 2) return true; } return false; } public static boolean isLevel2(String pwd) { return isLongEnough(pwd) && hasNoSpaces(pwd) && atLeastOneUpper(pwd) && atLeastOneLower(pwd) && atLeastOneDigit(pwd); } private static boolean isLongEnough(String pwd) { return pwd.length() >= 6; } private static boolean hasNoSpaces(String pwd) { return !pwd.contains(" "); } private static boolean atLeastOneUpper(String pwd) { for(int i = 0; i<pwd.length(); i++) { if(Character.isUpperCase(pwd.charAt(i))) { return true; } } return false; } private static boolean atLeastOneLower(String pwd) { for(int i = 0; i<pwd.length(); i++) { if(Character.isLowerCase(pwd.charAt(i))) { return true; } } return false; } private static boolean atLeastOneDigit(String pwd) { for(int i = 0; i<pwd.length(); i++) { if(Character.isDigit(pwd.charAt(i))) { return true; } } return false; }
现在你再运行测试用例,应该就能得到正确的返回值了。
内容的提问来源于stack exchange,提问作者user9211074
相关产品推荐
相关产品推荐

