Easy way to limit output to a specific integer without using if / else statements?
I have an assignment where I need to calculate grades. In the code block below, the user enters "sections" and multiplies it by 4, limiting the total output to 20. As intended, we cannot use if / else statements, but all I can think of is limiting the output to 20. Perhaps using simple Math method? But I cannot think of an easy way to do this.
public static int calcDGrade(int sections) //method to calculate the grade for the students sections
{
int maxDGrade = ((sections*4));
if (maxDGrade > 20) //limits total score to 20
{
return 20;
}
else
{
return maxDGrade;
}
}
source to share
You can use the ternary operator :
return maxDGrade > 20 ? 20 : maxDGrade;
The triple operation consists of the following parts:
condition ? A : B
where A is the result of the operation if the condition is evaluated as true
, and B
is the result if the condition is evaluated as false
.
In your example, it will return 20
if maxDGrade
greater than 20, otherwise it will return a value maxDGrade
. In other words, it is equivalent to saying:
if (maxDGrade > 20) {
return 20;
} else {
return maxDGrade;
}
source to share
You can use Math.min(int, int)
to get the minimum of 20 and a different value. Something like
int maxDGrade = Math.min(20, sections*4);
Because you want 20
or the result of the multiplication, which is ever lower.
source to share