Multiple conditions in ternary conditional operator?

后端 未结 7 864
醉酒成梦
醉酒成梦 2021-01-04 12:20

I am taking my first semester of Java programming, and we\'ve just covered the conditional operator (? :) conditions. I have two questions which seem to be wanting me to \"n

7条回答
  •  被撕碎了的回忆
    2021-01-04 13:09

    For the first question, you can indeed use the ternary operator, but a simpler solution would be to use a String[] with the month descriptions, and then subscript this array:

    String[] months = { "jan", "feb", "mar", ... };
    int month = 1; // jan
    String monthDescription = months[month - 1]; // arrays are 0-indexed
    

    Now, for your second question, the ternary operator seems more appropriate since you have fewer conditions, although an if would be much easier to read, imho:

    String year = "senior";
    if (credits < 30) {
      year = "freshman";
    } else if (credits <= 59) {
      year = "sophomore";
    } else if (credits <= 89) {
      year = "junior";
    }
    

    Contrast this with the ternary operator:

    String year = credits < 30 ? "freshman" : credits <= 59 ? "sophomore" : credits <= 89 ? "junior" : "senior";
    

提交回复
热议问题