3

Can someone please tell me why the switch statement is not recognizing the gat String variable. The IDE tells me that a primitive is required (int, char, short ....), but it found a string.

String gat = temp[i];

switch (gat) {
    case "a":
        output[i] = 12 * k;
        break;
    case "b":
        output[i] = 23 * k;
        break;
    case "c":
        output[i] = 34 * k;
        break;
}
3
  • 8
    Likely Java 6 is used as either the JDK or the target compiler. Pre-java 7 Strings were not allowed in switch statements Commented Nov 30, 2014 at 3:04
  • 2
    What is the error message? Commented Nov 30, 2014 at 3:10
  • stackoverflow.com/questions/21006136/… , this helped me Commented May 29, 2017 at 12:05

2 Answers 2

4

Your project compliance level is set to Java 6 or earlier, you cannot use String as case labels before Java 7. But, in the case of your question you might use charAt(0)

String gat=temp[i];
switch (gat.charAt(0))
{
case 'a':
    output[i] = 12 * k;
    break;
case 'b':
    output[i] = 23 * k;
    break;
case 'c':
    output[i] = 34 * k;
    break;
}
Sign up to request clarification or add additional context in comments.

Comments

0

If you are using NetBeans, make sure you have the latest JDK version. If you are using Eclipse, have the latest JDK version and set compliance level of the compiler in Java settings to 1.7.

Comments

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.