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

如何将Java嵌套if语句改写为含逻辑&&运算符的单if语句并实现相同输出

嵌套if转逻辑运算符改写的验证与修正

原嵌套if实现代码

这是用于考试分数判断的嵌套if语句代码:

public class NestIfExample {

    public static void main(String[] args) {
        Scanner inputDevice = new Scanner(System.in);
        
        // 提示用户输入分数
        System.out.print("Enter your score: ");
        int score = inputDevice.nextInt();

        // 外层if判断是否及格
        if (score >= 50) {
            System.out.println("You passed the exam!");

            // 内层if判断是否属于高分段
            if (score >= 80) {
                System.out.println("Great job! You scored in the top range.");
            } else {
                System.out.println("Good effort, but there's room for improvement.");
            }
        } else {
            System.out.println("Unfortunately, you did not pass. Try again next time.");
        }
    }
}

你尝试改写的代码

你将嵌套if改写为使用&&逻辑运算符的结构,代码如下:

public static void main(String[] args) {
    Scanner inputDevice = new Scanner(System.in);
    
    // 提示用户输入分数
    System.out.print("Enter your score: ");
    int score = inputDevice.nextInt();

    // 使用逻辑AND (&&)的单if语句
    if (score >= 80 && score >= 50) {
        System.out.println("You passed the exam!");
        System.out.println("Great job! You scored in the top range.");
    } else if (score >= 50) {
        System.out.println("You passed the exam!");
    } else {
        System.out.println("Unfortunately, you did not pass. Try again next time.");
    }
}

验证结果与修正

你的改写存在输出不一致的问题:原代码中当分数在50 <= score < 80区间时,会输出两句内容:

You passed the exam!
Good effort, but there's room for improvement.

而你的改写代码在该区间只输出了You passed the exam!,遗漏了第二句提示,所以不符合原逻辑的输出效果。

另外,score >= 80 && score >=50这个条件可以简化为score >=80,因为分数大于等于80必然满足大于等于50,逻辑与的后半部分是冗余的。

正确的改写版本

public static void main(String[] args) {
    Scanner inputDevice = new Scanner(System.in);
    
    // 提示用户输入分数
    System.out.print("Enter your score: ");
    int score = inputDevice.nextInt();

    if (score >= 80) {
        System.out.println("You passed the exam!");
        System.out.println("Great job! You scored in the top range.");
    } else if (score >= 50) {
        System.out.println("You passed the exam!");
        System.out.println("Good effort, but there's room for improvement.");
    } else {
        System.out.println("Unfortunately, you did not pass. Try again next time.");
    }
}

这个版本完全匹配原嵌套if的输出逻辑,同时通过多分支if结构替代了嵌套,也可以理解为隐含了逻辑与的判断(因为score >=50的分支只会在score <80的情况下进入,等价于score >=50 && score <80)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 05:43:20