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

如何让Java嵌套if代码仅输出单个成绩等级判定语句?

Java嵌套if实现单成绩等级输出

问题分析

你当前的代码会输出多个等级,核心原因是每个if条件满足时都会直接打印对应等级,然后继续执行内层的if判断。比如输入90时,分数同时满足>=60、>=70、>=80、>=90四个条件,因此四个等级会被依次打印。要实现仅输出单个等级,需要让每个分数只匹配唯一的等级区间,只执行一次打印操作。

修改后的代码

import java.util.Scanner;
public class nestedif {
    public static void main(String []args){
        Scanner sc = new Scanner(System.in);
        int tscore = sc.nextInt();

        if (tscore < 60) {
            // 不及格情况
            System.out.println("tae");
        } else {
            // 及格后判断具体等级
            if (tscore < 70) {
                System.out.println("D");
            } else {
                if (tscore < 80) {
                    System.out.println("C");
                } else {
                    if (tscore < 90) {
                        System.out.println("B");
                    } else {
                        // 90及以上
                        System.out.println("A");
                    }
                }
            }
        }
    }
}

代码说明

  1. 先判断不及格情况(<60),直接输出对应结果;
  2. 对于及格的分数,通过嵌套的else+if结构,从低到高划分等级区间:
    • 60≤分数<70 → D
    • 70≤分数<80 → C
    • 80≤分数<90 → B
    • 90及以上 → A
  3. 每个分数只会进入一个区间分支,执行一次打印,彻底避免多输出问题。

如果你更习惯从高到低判断,也可以用以下嵌套写法(逻辑完全一致):

import java.util.Scanner;
public class nestedif {
    public static void main(String []args){
        Scanner sc = new Scanner(System.in);
        int tscore = sc.nextInt();

        if (tscore >= 90) {
            System.out.println("A");
        } else {
            if (tscore >= 80) {
                System.out.println("B");
            } else {
                if (tscore >= 70) {
                    System.out.println("C");
                } else {
                    if (tscore >= 60) {
                        System.out.println("D");
                    } else {
                        System.out.println("tae");
                    }
                }
            }
        }
    }
}

内容的提问来源于stack exchange,提问作者レッド・ スワン

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 16:22:56