1

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

}
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
anonymous coder
  • 21
  • 1
  • 1
  • 3

3 Answers3

7

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.

Strikegently
  • 2,251
  • 20
  • 23
2

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

Michael Seiler
  • 650
  • 1
  • 5
  • 15
  • Many Thanks , I have tried if else statement , I am just trying to figure out if there is a option in case statement , as it makes simpler . – anonymous coder Feb 21 '18 at 13:52
1

As you can read in Java Language Specification here:

All of the following must be true, or a compile-time error occurs:

  1. Every case constant expression associated with a switch statement must be assignable (§5.2) to the type of the switch Expression.
  2. No two of the case constant expressions associated with a switch statement may have the same value.
  3. No switch label is null.
  4. At most one default label may be associated with the same switch statement.

In your code the first point is not satisfied. You might want to use if-else-if statement instead of switch here to perform proper checking of value stored in i.

Przemysław Moskal
  • 3,551
  • 2
  • 12
  • 21