Prabakaran Raja Prabakaran Raja - 4 months ago 24
Java Question

Switch statement in java accept which datatypes

I got a error in this code

System.out.println("enter grade ");
Scanner input2 = new Scanner(System.in);
String grade = input2.nextLine();
switch(grade)
{
case "a":
g=10;
break;
case "b":
g=8;
break;
default:
System.out.println("invalid grade");
break;
}


I am using eclipse kepler. It is giving me the correct output.

But the same code when written in eclipse helios, it says like :

Cannot switch on a value of type String. Only convertible int values or enum constants are permitted


Help me fixing this.

Answer

You are using JDK <1.7. Switch on Strings won't work below JDK's.

So shift to 1.7 or do not use String's in Switch case.

May be a char type suits for you, because you are using a single character in String for your need.

Look in that way. Then it turns

//logic to get grade char and then 
    switch (grade) {
            case 'a':
                g = 10;
                break;
            case 'b':
                g = 8;
                break;
            default:
                System.out.println("invalid grade");
                break;
            }
Comments