Java – multiple conditions in ternary conditional operators?
I'm in the first semester of Java programming. We just introduced the conditional operator (?:) condition I have two problems. It seems that I want to "nest" conditional operators in another one. These I can easily (but cumbersome) use if else if statements
1) "Suppose the month is an int variable with a value of 1 or 2 or 3 or 5... Or 11 or 12. Write an expression with a value of" Jan "or" Feb "or" Mar "or" APR "or a value based on the month of" may "or" Jun "or" Jul "or" Aug "or" SEP "or" OCT "or" Nov "or" Dec " (therefore, if the value of the month is 4, the value of the expression will be "APR") “
My idea looks like this:
(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":
I know this is not a complete expression, but I'm not sure how to express and handle so many conditions with operators
2) Suppose credit is an int - valued variable with a value of 0 or positive Write an expression with a value of "freshman" or "sophomore" or "junior" or "advanced" according to the value of credits In particular, if the credit value is less than 30, the value of the expression is "freshman"; 30-59 will be "sophomore", 60-89 will be "junior", and 90 or more will be "advanced"
Again, I've been playing with the best thing I can think of (and my probs lacks some necessary parentheses):
credits < 30 ? "freshman": credits >= 30 && <=59 ? "sophomore": credits >= 60 && <= 89 ? "junior": "senior"
I searched the database on Google, but I don't think there is a problem If I am wrong, please forgive me Codelab will not adopt switch case or if else if solutions. It always suggests that I should use the following conditions: Operators, but everywhere I see, I don't think of how to operate operators to deal with so many conditions We are not far away in this book, so if you can help me find a solution, it will be great if it can compare with the little I have learned so far
Solution
For the first problem, you can use ternary operators, but a simpler solution is to use string [] with month description 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 because you have fewer conditions, although if will be easier to read, IMHO:
String year = "senior"; if (credits < 30) { year = "freshman"; } else if (credits <= 59) { year = "sophomore"; } else if (credits <= 89) { year = "junior"; }
Compare it with ternary operators:
String year = credits < 30 ? "freshman" : credits <= 59 ? "sophomore" : credits <= 89 ? "junior" : "senior";