I take my first semester of Java programming, and we just looked at the conditions of a conditional statement (? :). I have two questions that seem to want me to “embed” conditional statements in eachother, which I could easily (but tediously) do with if-else-if statements.
1) "Assume that the month is an int variable whose value is 1 or 2 or 3 or 5 ... or 11 or 12. Write an expression whose value is" jan "or" feb "or" mar "or" mar ", apr" or "may" or "jun" or "jul" or "aug" or "sep" or "oct" or "nov" or "dec" depending on the value of the month. (So, if the month value was 4, then the value of the expression will be "apr".).
My idea looked something 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 an operator phrase can handle so many conditions.)
2) Suppose that loans are an int variable whose value is 0 or positive. Write an expression whose meaning is “freshman” or “sophomore” or “junior” or “senior” based on the cost of loans. In particular: if the value of loans is less than 30, the value of the expression is “freshman”; 30-59 will be a sophomore, 60-89 will be a junior, and 90 or more will be a senior.
once again, I played, and the best I can come up with is something like (and I have spaces in some brackets):
credits < 30 ? "freshman": credits >= 30 && <=59 ? "sophomore": credits >= 60 && <= 89 ? "junior": "senior"
I have Googled around and checked the database here, but I DO NOT THINK that there is something like this question; forgive me if I am wrong. The program (CodeLab) will not accept a Switch-Case or if-else-if solution, always suggesting to use a conditional expression ?: operator, but wherever I looked, I did not understand how to force the operator to handle so many conditions. We do not go far into this book, so if you guys could help me find a solution, it would be great if that were the case as soon as I found out about it.