Jon Snow
Jon Snow

Reputation: 240

Backtracking Switch Statement With String

So I'm writing a program that randomly generates a maze and then finds a solution for it. Part of my code includes a backtracking algorithm where I move back if I hit a dead end.

Everytime I move, I record the move ("N" for North, "NE" for Northeast, on and on) in a stack. For the backtracking, I pop the top element of the stack and use a switch statement to move the opposite direction of the direction popped.

When I try to compile my code, it gives me an error that the Stack object popped cannot be converted to int, but I have seen String used for switch statements in other programs. I thought the toString method would automatically convert the object to String for the switch statement. I have tried manually using toString with the popped value as the parameter but that didn't work either. Here is the code and error message.

switch(visitStack.pop())
{
//                      have to backtrack the opposite direction i previously went
    case "N":   nowR++;
                visited[nowR][nowC] = 'N';
                break;
    case "NE":  nowR++;
                nowC--;
                visited[nowR][nowC] = 'N';
                break;
    case "E":   nowC--;;
                visited[nowR][nowC] = 'N';
                break;
    case "SE":  nowR--;
                nowC--;
                visited[nowR][nowC] = 'N';
                break;
    case "S":   nowC--;
                visited[nowR][nowC] = 'N';
                break;
    case "SW":  nowR--;
                nowC++;
                visited[nowR][nowC] = 'N';
                break;
    case "W":   nowC++;
                visited[nowR][nowC] = 'N';
                break;
    case "NW":  nowR++;
                nowC++;
                visited[nowR][nowC] = 'N';
                break;
}

enter image description here

The blued out portion has personal details.

Upvotes: 0

Views: 124

Answers (1)

Rajan Kali
Rajan Kali

Reputation: 12953

For java versions below 7 it wont support Strings in Switch Case

Alternative would be else if ladder to compare strings using .Equals() method

or

you can Use Enums in Switch Case

Upvotes: 1

Related Questions