Search code examples
javaif-statementternary

else if in Ternary


I was writing this code and I couldn't help but wonder if I can use else if statement in the ternary function.

I would like to print out 1 as 1st, 2 as 2nd, and 3 as 3rd, 4-10 as 4-10th.

Would it be possible to do it all in ternary or is it impossible?

 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;
    }

Solution

  • if your grades are between 1 and 10, then you can use a sufixArray, for numbers higher than 10 you need to promote x1,x2,and x3 to "th"-cardinal ending

    Example:

    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]);
    }
    

    the pros of using this instead of nesting ternary operator is the cyclomatic complexity, if you latter want to change any logic condition in the nested code, the probability you break your code is higher than when using just modulo operations.

    the snippet will print out:

    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:

    which is the cardinal order you are looking for...