Morchul
Morchul

Reputation: 2037

function in case condition

I have a kind of Tree:

public static final String CREATURES = "11";
public static final String NPC = "111";
public static final String PLAYER = "112";
public static final String OBJECTS = "12";
public static final String OBJECT = "121";
public static final String WEAPON = "1221";
public static final String SWORD = "12211";
public static final String BOW = "12213";

This is the Type class which hold the type number(identifier):

private String identifier;
public Type(String identifier){
    this.identifier = identifier;
}

And this is the function to check if Type isType of something:

public boolean isType(String otherIdentifier){
    if(this.identifier.length() < otherIdentifier.length()) return false;
    for(int i = 0; i < otherIdentifier.length(); ++i){
        if(otherIdentifier.charAt(i) != this.identifier.charAt(i)){
            return false;
        }
    }
    return true;
}
//identifier and otherIdentifier are the numbers for example 112 by Player

So SWORD is type of WEAPON and OBJECTS but not type of NPC for example.

Now I need to check which type it is:

public void doSomething(Type type){
    if(type.isType(Type.WEAPON)){
        //do something with weapon
    } else if(type.isType(Type.CREATURES)){
        //do something with Creature
    } ...
}

Now I wonder if I can do it with switch statement like:

switch(type){
    case .isType(WEAPON) : /* do something */ break;
    case .isType(CREATURES) : /* do something */ break;
    ...
}

Is this possible, or must I do it with if else statements?

Upvotes: 0

Views: 54

Answers (1)

MageXellos
MageXellos

Reputation: 154

It only supports constant

You just need read the official doc at here: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings).

Upvotes: 2

Related Questions