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

Java字符串比较问题:if分支未触发,始终执行else分支

Java参军资格判断代码的分支触发问题解决

你的代码问题出在字符串比较的方式上:用==判断字符串内容是否相等是错误的,这会导致输入"indian"时始终进入else分支。

问题原因

在Java中,String是引用类型,==运算符比较的是两个对象的内存地址,而不是字符串的实际内容。通过Scanner.nextLine()获取的输入字符串,和代码里的字面量"indian"虽然内容相同,但属于不同的对象实例,内存地址不一致,因此nationality == "indian"的结果永远是false。

解决方案

改用String.equals()方法比较字符串内容,该方法会逐一比对两个字符串的每个字符是否一致。如果希望忽略大小写(比如用户输入"Indian"、"INDIAN"也能通过判断),可以使用equalsIgnoreCase()方法,体验更友好。

修正后的代码

import java.util.Scanner;
public class orOperator {
    public static void main(String args[]) {
        System.out.println(" This code is to check you are eligible or not");
        Scanner buddha2 = new Scanner(System.in);
        System.out.println("Please enter your nationality");
        String nationality = buddha2.nextLine();
        System.out.println("you are " + nationality);
        // 改用equals()比较字符串内容,把字面量放前面可避免空指针异常
        if ("indian".equals(nationality)) {
            System.out.println("you are eligible to join the indian army");
        } else {
            System.out.println("Your are not eligible to join the army");
        }
    }
}

如果要支持大小写不敏感的判断,修改if条件为:

if ("indian".equalsIgnoreCase(nationality)) {

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 02:33:15