else if 在三元中

else if in Ternary

我在写这段代码的时候忍不住想知道我是否可以在三元函数中使用 else if 语句。

我想打印出 1 作为第 1,2 作为 2,3 作为 3,4-10 作为 4-10。

是否有可能用三进制全部完成还是不可能?

 while (gradeCounter <= 10){

        System.out.printf(gradeCounter==1?"Enter %dst grade: ":"Enter %dth grade : ", gradeCounter);
        //how can I do "else if" in ternary function
        int grade = input.nextInt();
        total = total + grade;
        gradeCounter = gradeCounter + 1;
    }

如果你的成绩在 1 到 10 之间,那么你可以使用后缀数组,对于高于 10 的数字,你需要将 x1、x2 和 x3 提升到“th”基数结尾

示例:

String[] cardinalSufixes = new String[]{ "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th" };
for (int i = 1; i <= 10; i++) {
    System.out.printf("Enter %d%s grade: \n", i, cardinalSufixes[i % 10]);
}

使用这个而不是嵌套三元运算符的优点是 cyclomatic complexity,如果您稍后想更改嵌套代码中的任何逻辑条件,您可能break your code 比仅使用模运算时更高。

代码段将打印出来:

Enter 1st grade: Enter 2nd grade: Enter 3rd grade: Enter 4th grade: Enter 5th grade: Enter 6th grade: Enter 7th grade: Enter 8th grade: Enter 9th grade: Enter 10th grade:

哪个是您要查找的基本顺序...