账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    关于Java中if-else的优化问题
    40
    0

    问题描述

    这是一个比较简单的题目,都会写,我想问的是,这些if-else能否优化

    相关代码

    // 请把代码文本粘贴到下方(请勿用图片代替代码)

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.println("Enter the number of students:");
        int n = input.nextInt();
        int[] score = new int[n];
        System.out.println("Enter scores:");
    
        int max = 0;
        for (int i = 0; i < n; i++) {
            score[i] = input.nextInt();
            if (score[i] > max) {
                max = score[i];
            }
        }
    
        for (int i = 0; i < n; i++) {
            if (score[i] >= max - 10)
                System.out.println("Student " + i + " score is " + score[i] + " and grade is A");
            else if (score[i] >= max - 20 && score[i] < max - 10)
                System.out.println("Student " + i + " score is " + score[i] + " and grade is B");
            else if (score[i] >= max - 30 && score[i] < max - 20)
                System.out.println("Student " + i + " score is " + score[i] + " and grade is C");
            else if (score[i] >= max - 40 && score[i] < max - 30)
                System.out.println("Student " + i + " score is " + score[i] + " and grade is D");
            else
                System.out.println("Student " + i + " score is " + score[i] + " and grade is F");
        }
    
    
    }
    
    1
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 赠瑰留香 普通会员 1楼
      502 Bad Gateway

      502 Bad Gateway


      nginx
    更多回答
    网站公告
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部