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
Put your code in brackets and add null at the end and you're golden.
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.
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.
(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.
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";
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.