3

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.

7 Answers 7

11

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;
            }
Sign up to request clarification or add additional context in comments.

Comments

1

Switch statements with String cases have been implemented in Java SE 7. SO check your JDK in eclipse.

Comments

1

you may be using jdk which is less than 1.7,check your java version in the following way

  • right click on your project
  • click configure build path then go to libraries and check which jdk
    does your eclipse use.

If it is less than 1.7 then give the path for 1.7

Comments

0

Just change String to char.

case "a":

to

case 'a':

Strings are not accepted in switch before Java 7, but chars are.

Comments

0

Change your string to char, and "" to ''

char c = grade.charAt(0);

switch(c)
{
.
.
}

Comments

0

In Eclipse Mars, I didn't use " " at all for int type.

int grade;
switch(grade)
{
 case 1:
 break;
 case 2:
 break;
 default:
 break;
}

Hope it will work for others

Comments

0

For string cases you can use, for example:

String choice;
switch(choice)
{
case "1": 
  break;
case "2":
  break;
default: break;
}

1 Comment

While code-only answers are not forbidden, please understand that this is a Q&A community, rather than a crowd-sourcing one, and that, usually, if the OP understood the code being posted as an answer, he/she would have come up with a similar solution on his/her own, and wouldn't have posted a question in the first place. As such, please provide context to your answer and/or code by explaining how and/or why it works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.