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

Java用户认证循环异常:首次输错后正确用户名仍提示错误

用户认证代码问题修复

问题根源

  • 首次输入错误用户名后,进入else块的do-while循环,但循环内仅调用in.nextLine()读取输入,未将新输入的值赋值给username变量。因此循环中username始终是第一次输入的错误值,即便第二次输入正确,判断条件仍会判定用户名错误,无法进入密码输入环节。
  • 密码验证成功后,System.exit(0)放在提示语句之前,导致加载提示永远无法被执行。

修复后的代码

import java.util.Scanner;
class User_Authentication
{
    public static void main(String args[])
    {
        Scanner in = new Scanner(System.in);
        String username;
        
        // 循环获取用户名,直到输入正确
        do {
            System.out.println("Enter your Username");
            username = in.nextLine();
            if (!username.equals("xyz")) {
                System.out.println("Incorrect username");
                System.out.println("Please try again");
            }
        } while (!username.equals("xyz"));
        
        // 用户名正确,进入密码验证流程
        System.out.println("Enter the Password");
        String password = in.nextLine();
        if (password.equals("xyz1234")) {
            System.out.println("Welcome");
            System.out.println("Please wait while the system is loading....");
            System.exit(0);
        } else {
            System.out.println("Your system has been locked for security reasons.");
            System.out.println("Please contact an administrator to reset the password");
            System.out.println("Any attempt to break in the computer will result in self destruction.");
            System.exit(0);
        }
    }
}

修复说明

  1. 重构用户名输入逻辑:将用户名输入放入do-while循环内,每次输入后更新username变量,确保判断条件基于最新输入值。
  2. 调整退出语句位置:将System.exit(0)移至提示输出之后,保证用户能看到加载提示内容。
  3. 简化代码结构:移除冗余分支判断,让整体逻辑更清晰易懂。

内容的提问来源于stack exchange,提问作者ShelbyCodersPrivate.ltd

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 01:01:07