I am learning java and I am having trouble with switch-case statement with expression. Can someone help me please? I am not able to understand where I am making the mistake.
package SecondSet_StartingArray;
import java.util.Scanner;
public class Testing
{
public static void main(String[] args) {
System.out.println("Enter a Number between 1 & 100");
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
switch (i)
{
case (i>90): System.out.println("Rating 5");break;
case (i<=90): System.out.println("Rating 4");break;
case (i<=60): System.out.println("Rating 3");break;
case(i<=30): System.out.println("Rating 2");break;
case(i>29): System.out.println("Rating 1");break;
}
}
}
You can't use switch-case with boolean expressions like case (i<=90). Your cases must be constant expressions to be evaluated.
case 90: whatever; break;
case 120: whatever; break;
case SOME_CONSTANT: whatever; break;
For your needs, you would need to use if-else-if statements.
What you are trying to realize is an if-else-statement. Switch-Statements are used when you try to evaluate constant values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With