You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 11:01:25