Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch statement is not accepting String variable

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;
}
like image 378
matt lao Avatar asked Mar 02 '26 09:03

matt lao


1 Answers

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;
}
like image 149
Elliott Frisch Avatar answered Mar 04 '26 23:03

Elliott Frisch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!