Multiple conditions in ternary conditional operator?
(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.
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.
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.