Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch statement with boolean expressions in case labels [duplicate]

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

}
like image 669
anonymous coder Avatar asked May 23 '26 10:05

anonymous coder


2 Answers

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.

like image 121
Strikegently Avatar answered May 24 '26 22:05

Strikegently


What you are trying to realize is an if-else-statement. Switch-Statements are used when you try to evaluate constant values.

like image 31
Michael Seiler Avatar answered May 24 '26 22:05

Michael Seiler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!