Reputation: 3
Just started writing code in java and is learning normal logic operations. While using a switch case I wanted to specify a range and am not able to do it. switch (input){ case 0-20 : System.out.println("Your grade is F"); break;
case 21-40 :
System.out.println("Your grade is D");
break;
case 41-60 :
System.out.println("Your grade is C");
break;
case 61-80 :
System.out.println("Your grade is B");
break;
case 81-100 :
System.out.println("Your grade is A");
break;
Can anybody help me
Upvotes: 0
Views: 3043
Reputation: 1251
The Java switch { case:
wasn't designed to use ranges.
You can use a chain of if ... else if
like this:
if (input >= 81) System.out.println ("Congratulations! Your grade is A");
else if (input >= 61) System.out.println ("Your grade is B");
else if (input >= 41) System.out.println ("Your grade is C);
Note this uses the suggestion from the comment from WJS. If you code several lines like this
else if (input >= 61 && input <= 80) ...
, there is a greater chance of making a typo and introducing a bug.
However, in this case, the fact that the range is always 20 points allows you to use a little math to fit a switch
block:
int k = (input - 1) / 20;
switch (k) {
case 0:
System.out.println ("Your grade is F. So sorry.");
break;
case 1:
System.out.println ("Your grade is D");
break;
case 2:
System.out.println ("Your grade is C");
break;
and so on.
If I may, I'd like to offer some suggestions outside the scope of your question.
Instead of having multiple lines that all include "Your grade is ", calculate the grade as a single character or a String
that contains a single character:
int k = (input - 1) / 20;
char grade;
switch (k) {
case 0:
grade = 'F';
break;
case 1:
grade = 'D';
break;
case 2:
grade = 'C';
break;
and so on. It would be followed by
System.out.println ("Your grade is " + grade);
Here is a way to avoid both if ... else
chain and switch
block.
char [] grade = {'F','D','C','B','A'};
...
int k = (input - 1) / 20;
System.out.println ("Your grade is " + grade [k]);
This assumes there is something to guard against the possibility that input
will be less than zero or greater than 100.
Upvotes: 2