Java大小写不敏感3次尝试密码验证程序功能问题咨询
问题解决:密码大小写不敏感验证
核心修复点
原代码使用equals()方法做密码比对,该方法区分大小写,要实现大小写不敏感验证,只需将所有equals()替换为equalsIgnoreCase()即可。同时修复原代码中冗余Scanner实例、输入读取异常的问题。
修改后的完整代码
import java.util.Scanner; public class PasswordValidator { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int attempts = 3; String inputPassword = ""; System.out.println("Please set your password."); String storedPassword = sc.nextLine(); while (attempts > 0) { System.out.print("Enter your password: "); inputPassword = sc.nextLine(); if (inputPassword.equalsIgnoreCase(storedPassword)) { System.out.println("Access Granted"); System.out.println("Secret: Water is not Wet."); break; } else { attempts--; if (attempts > 0) { System.out.println("Incorrect. Number of attempts remaining: " + attempts); } else { System.out.println("You have entered too many incorrect passwords, please try again later."); } } } sc.close(); } }
关键修改说明
- 替换比对方法:用
equalsIgnoreCase()替代equals(),该方法会忽略字符串大小写完成比对,直接满足需求。 - 简化输入处理:移除冗余的
Scanner实例,只用一个实例处理所有输入,避免资源浪费和空行读取异常。 - 优化循环逻辑:调整次数递减时机,让剩余尝试次数的显示更准确,验证成功后直接跳出循环,减少无效执行。
- 规范资源管理:添加
sc.close()关闭输入流,养成良好的资源使用习惯。
内容的提问来源于stack exchange,提问作者Ehxo
相关产品推荐
相关产品推荐

