Pregunta

I am developing a Java Class. Can I please have some help in using a Switch statement with a String data type.

Here is my code:

    String testString = "Nut";
    switch (testString)
    {
        case "Nut":
            if(NutCount < NutMaxCount) 
                NutCount += 1;
            break;
        case "Caramel":
            if(CaramelCount < CaramelMaxCount)
                CaramelCount += 1;
            break; 
        case "Chocolate":
            if(ChocolateCount < ChocolateMaxCount)
                ChocolateCount += 1;
            break;
        case "Marzipan":
            if(MarzipanCount < MarzipanMaxCount)
                MarzipanCount += 1;
            break;                        
    }

This is the error I am getting:

incompatable types - found java.lang.String but expected int.

¿Fue útil?

Solución 2

This link will lead you to Java 7: http://www.oracle.com/technetwork/java/javase/downloads/index.html

You will require Java 7, so you can use Strings in a switch statement.

When you create a new project in your IDE (the ide in the picture is eclispse) make sure you select a Java that ends with 1.7

enter image description here

or

Just make each string correspond to a int value.

Otros consejos

Switch case with String only works with Java7

Alternatively, you can use enum instead for any version earlier than Java7

String testString = "Nut";
ValueEnum enumval = ValueEnum.fromString(testString);
switch (enumval) 
{
   case Nut:
            if(NutCount < NutMaxCount) 
                NutCount += 1;
            break;
   case Caramel:
            if(CaramelCount < CaramelMaxCount)
                CaramelCount += 1;
            break; 
   case Chocolate:
            if(ChocolateCount < ChocolateMaxCount)
                ChocolateCount += 1;
            break;
   case Marzipan:
            if(MarzipanCount < MarzipanMaxCount)
                MarzipanCount += 1;
            break;
}

String type isn't allowed to use as switch condition before JDK7,
so please use an Integer variable to instead of.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top