缩短我的if语句

时间:2015-03-04 17:58:04

标签: java

我想让人们投入他们的作业并根据这些数字进行评分。我需要一个if语句告诉他们他们的成绩。这就是我到目前为止所拥有的。一切正常我只需要缩短if语句。这就是我所拥有的:

if (pC >= 93 ) 
        {
            System.out.print("\n Your grade is an A");
        }
        else if (pC >= 90) 
        {
            System.out.print("\n Your grade is a A-");
        }
        else if (pC >= 87)
        {
            System.out.print("\n Your grade is a B+");
        }
        else if (pC >= 83)
        {
            System.out.print("\n Your grade is a B");
        }
        else if (pC >= 80)
        {
            System.out.print("\n Your grade is a B-");
        }
        else if (pC >= 77)
        {
            System.out.print("\n Your grade is a C+");
        }
        else if (pC >= 73)
        {
            System.out.print("\n Your grade is a C");
        }
        else if (pC >= 70)
        {
            System.out.print("\n Your grade is a C-");
        }
        else if (pC >= 67)
        {
            System.out.print("\n Your grade is a D+");
        }
        else if (pC >= 63)
        {   
            System.out.print("\n Your grade is a D");
        }
        else if (pC >= 60)
        {
            System.out.print("\n Your grade is a D-");
        }
        else if (pC <= 59)
        {
            System.out.print("\n Your grade is a F");
        }

3 个答案:

答案 0 :(得分:8)

您可以构建一个阈值和成绩标签表。

final int [] lbound =   {93, 90, 87, 83, 80, 77, 73, 70, 67, 63, 60, Integer.MIN_VALUE};
final String [] label = {"n A", " A-", " B+", " B", " B-", " C+", " C", " C-", " D+", " D", " D-", " F"};

for (int i = 0; i < lbound.length; ++i) {
    if (pC >= lbound[i]) {
        System.out.print("\n Your grade is a" + label[i]);
        break;
    }
}

答案 1 :(得分:3)

您的代码包含许多易于消除的冗余。逻辑的本质是从测试分数到成绩的映射,所以你需要一个表达式或一个只是那个的函数而不需要其他任何东西,然后其余的代码就会以统一的形式进行打印办法。如果您对硬编码值感到满意,那么格式正确的条件表达式是最干净的:

String grade = 
      pC >= 93 ? "A"
    : pC >= 90 ? "A-"
    : pC >= 87 ? "B+"
    : pC >= 83 ? "B"
    : pC >= 80 ? "B-"
    : pC >= 77 ? "C+"
    : pC >= 73 ? "C"
    : pC >= 70 ? "C-"
    : pC >= 67 ? "D+"
    : pC >= 63 ? "D"
    : pC >= 60 ? "D-"
    : "F";    
System.out.println("\n Your grade is a "+grade);

答案 2 :(得分:2)

我在评分系统中看到一个模式,可用于构建数据结构:

  • 十位数位决定成绩 - A(超过90),或B(超过80,但小于90),等......
  • 地点数字决定子标记 - +(7或更多),-(0到3)或普通等级(3到5)。

您可以构建2个存储这些映射的地图:

// These two maps can be moved to a common better place
TreeMap<Integer, String> gradeMapRules = new TreeMap<Integer, String>();
gradeMapRules.put(9, "A");
gradeMapRules.put(8, "B");
gradeMapRules.put(7, "C");
gradeMapRules.put(6, "D");
gradeMapRules.put(0, "F");

TreeMap<Integer, String> subGradeMapRules = new TreeMap<Integer, String>();
subGradeMapRules.put(0, "-");
subGradeMapRules.put(3, "");
subGradeMapRules.put(7, "+");

然后给出一个标记,你可以得到它的等级:

int pC = 75;
String grade = gradeMapRules.floorEntry(pC / 10).getValue();
String subGrade = !"F".equals(grade) ? subGradeMapRules.floorEntry(pC % 10).getValue() : "";
String finalGrade = grade + subGrade;