Switch statement does not accept a String variable

Can someone please tell me why the switch statement doesn't recognize the gat

String variable . IDE

tells me there primitive

is required

(int, char, short ....) but it found the 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


source to share


2 answers


Your project's compliance level is set to Java 6 or earlier, you cannot use String

as case shortcuts before Java 7. But in case of your question, you can usecharAt(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;
}

      

+4


source


If you are using NetBeans, make sure you have the latest JDK installed. If you are using Eclipse use the latest JDK and set the compiler compliance level in Java preferences to 1.7.



0


source







All Articles