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