Nongthonbam Tonthoi
Nongthonbam Tonthoi

Reputation: 12953

How to use int value from Map in switch case?

I have a map:

Map<String, Integer> myMap = new HashMap<String, Integer>();

Now I have added some values:

myMap.put("east", generateId());
myMap.put("west", generateId());
myMap.put("north", generateId());
myMap.put("south", generateId());

Now I am trying to check for matches using switch case:

int i = myMap.get("east");
int j = myMap.get("west");
int k = myMap.get("north");
int l = myMap.get("south");
switch (myId) {
    case i:
        break;
    case j:
        break;
    case k:
        break;
    case l:
        break;
}

It says constant expression required at all the cases(i, j, k, l). How do I resolve this?

Upvotes: 2

Views: 2841

Answers (4)

OldCurmudgeon
OldCurmudgeon

Reputation: 65851

Are you certain you have your map the right way around?

    Map<Integer, String> myMap = new HashMap<>();
    myMap.put(generateId(), "east");
    myMap.put(generateId(), "west");
    myMap.put(generateId(), "north");
    myMap.put(generateId(), "south");
    switch (myMap.get(1)) {
        case "north":
            break;
        case "south":
            break;
        case "east":
            break;
        case "west":
            break;
    }

Upvotes: 1

Adnan Isajbegovic
Adnan Isajbegovic

Reputation: 2307

Since you can only use values in switch case, not variables, you must change your code:

Set<Integer> set = new HashSet<Integer>(myMap.size());
set.add(new Integer(myMap.get("east")));
set.add(new Integer(myMap.get("west")));
set.add(new Integer(myMap.get("north")));
set.add(new Integer(myMap.get("south")));

if (set.contains(new Integer(myId))) break;

You can use Set to help you with checking (works in O(1), and there is less code). Also, switch is not OOP so don't use it...

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234785

You can't. The case labels must be compile-time evaluable constant expressions, and the values of i etc. are only known at run-time.

Use a series of if else statements instead.

if (myId == i){ etc.

Upvotes: 6

Zircon
Zircon

Reputation: 4707

values used for case statements must be constants, meaning they must be unable to be changed throughout the statement. You can fix this problem by making your one-letter variables final.

Upvotes: -3

Related Questions