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

Java登录程序密码输入模块if/else分支失效问题排查求助

问题分析与修复方案

我一眼就发现问题所在了——你的Scanner使用方式踩了个经典的小坑!

为什么第二个else if分支永远不工作?

当你调用passwordInput.nextInt()的时候,Scanner会读取并消耗掉输入流中的那个整数。也就是说,第一个if条件里的passwordInput.nextInt()已经把用户输入的数字从Scanner里取走了,输入流直接空了。

举个例子:如果用户输入了错误的密码1234,第一个if里的hasNextInt()是true,然后调用nextInt()拿到1234,和内置密码1254不相等,所以第一个if不成立。接下来进入else if分支时,Scanner里已经没有任何输入了,hasNextInt()直接返回false,自然就跳过这个分支,直接走到else里输出格式错误——这完全不是你想要的结果!

修复后的代码

解决思路很简单:先把用户的输入读取出来存到变量里,再用这个变量做判断,不要反复调用nextInt()消耗输入流。

import java.util.Scanner;
public class Password {
    public static void main(String[] args) {
        Scanner passwordInput = new Scanner(System.in);
        System.out.print("Please enter your password: ");
        int builtInPassword = 1254;
        
        // 先检查输入格式,再一次性读取输入
        if (passwordInput.hasNextInt()) {
            int inputPassword = passwordInput.nextInt();
            // 用存储好的变量做判断,避免重复消耗输入
            if (inputPassword == builtInPassword) {
                System.out.println("Your password is correct.");
            } else {
                System.out.println("The password entered is incorrect");
            }
        } else {
            System.out.println("Sorry, please enter the right format");
        }
    }
}

修复逻辑说明

  1. 先通过hasNextInt()判断用户输入是否是整数格式,这一步不会消耗输入流
  2. 如果格式正确,就用nextInt()把输入读取到inputPassword变量里,这时候才消耗输入流
  3. 最后用这个变量和内置密码比较,就能正确触发“密码正确”和“密码错误”两个分支,格式不对的情况也会正常走到else分支

这样修改后,三个分支都能正常工作啦!

内容的提问来源于stack exchange,提问作者Neamat Tabani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:07:09