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

Java代码中if语句运行异常如何排查修复?

问题排查与修复方案

存在的3个核心错误

    1. Scanner输入残留换行符问题
      调用scanner.nextInt()方法只会读取输入的整数,不会吃掉输入结束时按下的回车键产生的换行符,后续执行scanner.nextLine()时会直接读取到残留的空换行符,导致name变量拿到的是空值,永远匹配不到预设的字符串。
    1. 字符串比较方式错误
      Java中==运算符比较的是字符串对象的内存地址,不是字符串的内容,除了判断"Dean"的分支用了正确的equals()方法外,剩下三个名字判断都用了==,就算name拿到了正确的输入值,也大概率匹配失败。
    1. 分支逻辑错误
      选择输入1(选手编号)时不需要读取姓名,选择输入2(选手姓名)时不需要读取编号,但原代码不管用户选1还是2,都会执行读取jersey和name的代码,完全不符合设计逻辑。

修复后的完整代码

import java.util.Scanner;

public class MarylandBaseball {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print( "Type 1 to enter a number or 2 to enter a name: " ) ;
        int choice = scanner.nextInt() ;
        // 吃掉nextInt残留的换行符
        scanner.nextLine();

        if (choice == 1) {
            System.out.print("Enter player number: ");
            int jersey = scanner.nextInt();
            if (jersey == 42) System.out.print("Which player wears number 42 on his jersey?");
            else if (jersey == 11) System.out.print("Which player wears number 11 on his jersey?");
            else if (jersey == 6) System.out.print("Which player wears number 6 on his jersey?");
            else if (jersey == 4) System.out.print("Which player wears number 4 on his jersey?");
        } else if (choice == 2) {
            System.out.print("Enter player name: ");
            String name = scanner.nextLine();
            if (name.equals("Dean")) System.out.print("What number does Dean wear?");
            else if (name.equals("Alleyne")) System.out.print("What number does Alleyne wear");
            else if (name.equals("Shaw")) System.out.print("What number does Shaw wear");
            else if (name.equals("Costes")) System.out.print("What number does Costes wear");
        }
        scanner.close();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 03:30:01