如何改善if-else链条?

时间:2016-02-05 01:45:18

标签: java

编辑:我认为if语句可能会出现在主类中,我仍然不知道该怎么做。

我有这个项目,我已经序列化了一个arrayList,然后对其进行了反序列化。

现在我被困在如何通过它并获得某些价值观。

代码如下:

        grade =  deserStudents.getGrade();
        firstName = deserStudents.getFirstName();
        lastName = deserStudents.getLastName();         

        if(grade > 0 && grade < 1) {
            letterGrade = "F";
        }

        else if(grade >= 1 && grade < 2) {
            letterGrade = "D";
        }

        else if(grade >= 2 && grade < 2.3) {
            letterGrade = "C";
        }               

        else if(grade >= 2.3 && grade < 2.7) {
            letterGrade = "C+";
        }

        else if(grade >= 2.7 && grade < 3) {
            letterGrade = "B-";
        }

        else if(grade > 3 && grade < 3.3) {
            letterGrade = "B";
        }

        else if(grade >= 3.3 && grade < 3.7) {
            letterGrade = "B+";
        }

        else if(grade >= 3.7 && grade < 4) {
            letterGrade = "A";
        }

        else if(grade > 4 && grade <= 4.3) {
            letterGrade = "A+";
        }
        else {
            assert false : " Invalid grade " + grade;
        }

        System.out.println("- " +firstName+ " - " + lastName+ " - " + grade + " - " + letterGrade);         

正如你在DeSerielizationHelper中看到的,我应该这样做的方式是一个巨大的if / else语句。我似乎无法找到一种方法来提取deserStudents的等级,名称。有人知道修复吗?

由于

1 个答案:

答案 0 :(得分:1)

您不需要if上的双重条件。

    if(grade < 0) {
        assert false : " Invalid grade " + grade;
    }
    else if(grade < 1) {
        letterGrade = "F";
    }
    else if(grade < 2) {     // we already know grade >= 1
        letterGrade = "D";
    }
    else if(grade < 2.3) {   // we already know grade >= 2
        letterGrade = "C";
    }               

除此之外,您可以做的另一件事是创建一个包含阈值和相应值的数组。然后使用for循环迭代它们并执行if条件。

// X stands for invalid (when grade is below 0 or above 4.3
double [] values = {0, 1, 2, 2.3};        // etc etc
String [] grades = {"X", "F", "D", "C"};  // etc etc
letterGrade == "X";                       // Set it to invalid in case it's above 4.3

for(int i=0; i<values.length; i++){
    if(grade<values[i]){ 
        letterGrade=grades[i]; 
        break; 
    }
}

// if invalid, throw error
if("X".equals(letterGrade)) 
    assert false : " Invalid grade " + grade;