Multiple conditions in ternary conditional operator?

半城伤御伤魂 提交于 2019-12-01 04:21:35

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

Parentheses are like violence: if it's not working, use more.

But seriously:

( condition A ? value A :
  ( condition B ? value B : 
    ( condition C ? value C :
       ...
    )
  )
)

And please, don't ever write code like that for anything important.

(month==1)?"jan":(month==2)?"feb": (month==3)?"mar": (month==4)?"apr": (month==5)?"may":(month==6)?"jun": (month==7)?"jul":(month==8)?"aug": (month==9)?"sep": (month==10)?"oct": (month==11)?"nov": (month==12)?"dec":null

you got it right, the only thing you need is the null at the end when you finish thats all.

Jurgen Ermans

I had the same question at my study. Thanks for the info about if and else. Would be my choice too except the assignment is asking us specificly to use the conditional operators. so basically they're asking us to write it in an unreadable way.

(credits < 30) ? "freshman" : (credits >= 30 && credits < 60) ?"sophomore" : (credits >= 60 && credits < 90) ? "junior" : "senior"

This was mine and its correct. I am wondering though if there is a shorter piece of code (using only the conditional operators.).

By the way Evan your code was almost good. just missed some brackets around each expression.

You are handling the idea of a if-else-if situation in a ternary correctly, but your syntax was slightly off (as you said it might be).

I would, however, change it slightly so that extra conditions aren't checked unnecessarily.

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

But your best option is just to use if and else statements for the sake of code readability.

Put your code in brackets and add null at the end and you're golden.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!