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

为何Java方法内的密码验证循环无法正常运行?

密码验证循环失效问题分析与修复

问题根源

你的代码存在三个核心问题导致循环仅执行一次就终止:

  • 输入仅读取一次:main方法里只在程序启动时获取一次密码,后续循环全程使用这个固定值,无法接收新的输入尝试。
  • 错误时直接终止程序:密码错误且未到第三次尝试时,代码调用exit(0)直接退出,循环没有继续执行的机会。
  • 逻辑分支冲突:!passkey.equals("TerrorX")的分支会覆盖其他情况,只要密码错误且不是第三次尝试,就直接触发程序退出,循环流程被打断。

修正后的代码

import java.util.Scanner;

public class Main {

    public static void password() {
        Scanner input = new Scanner(System.in);
        int attempts = 0;
        final String CORRECT_PASSWORD = "TerrorX";
        
        while (attempts < 3) {
            attempts++;
            System.out.println("请输入密码:");
            String passkey = input.nextLine();
            
            if (passkey.equals(CORRECT_PASSWORD)) {
                System.out.println("Welcome Master Puneet\nI am really happy to see you here");
                return; // 验证成功,退出方法
            } else if (attempts == 3) {
                System.out.println("You have exceeded multiple attempts");
            } else {
                System.out.println("Invalid Passphrase\nKindly Try Again");
            }
        }
        // 三次失败后退出程序
        System.exit(0);
    }

    public static void main(String[] args) {
        System.out.println("Welcome to Self Taught AI");
        System.out.println("Creator Puneet Sharma");
        System.out.println("To Proceed further Please enter your passkey");
        
        password();
    }
}

关键修正点

  1. 循环内读取输入:把Scanner的输入读取逻辑移到循环内部,每次循环都能获取用户新的输入,支持多次尝试。
  2. 移除不必要的退出调用:仅在三次尝试全部失败后调用System.exit(0),验证成功时用return退出方法即可,保留程序正常流程。
  3. 简化逻辑分支:调整判断顺序,先验证密码正确性,再判断是否是最后一次尝试,避免分支冲突,逻辑更直观。
  4. 常量定义正确密码:将正确密码定义为常量,减少硬编码重复,便于后续维护。

内容的提问来源于stack exchange,提问作者Puneet Sharma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 20:40:21