L457
L457

Reputation: 1032

Java: how to access a variable which was declared inside a switch statement

I'm not sure if I am doing this right, but I keep getting an error saying my array "currentRoute" cannot be resolved into a variable. I'm assuming this is because I have declared the array in a different scope. Is there any way I can get this to work while still declaring the variable in within my switch statement and while still using a simple array? (I cannot use an arraylist, as the rest of my code would be affected)

    switch (routeID)
    {
        case "1" : {
            String[] currentRoute = new String[Route1.length];
            currentRoute = Route1;
        }
        case "96" : {
            String[] currentRoute = new String[Route96.length];
            currentRoute = Route96;
        }
    }

    // print out values in currentRoute
    for (int i = 0; i < currentRoute.length; i++)
    {
        System.out.println(currentRoute[i]);
    }

there are a lot more switch statements, but I have just included 2 for this example.

EDIT:both switch and for statements are located within the same method.

Upvotes: 3

Views: 3098

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

Your case labels define an inner local scope by using curly braces. A general rule in Java is that you cannot access variables from an inner scope when you are in the outer scope (however, variables from the outer scope defined before the inner scope remain visible). Therefore, there is no way to access currentRoute defined inside the switch.

The solution is to define currentRoute outside the switch, do the assignment inside the switch, and keep accessing the variable after the switch is over:

String[] currentRoute;
switch (routeID) {
    case "1" : {
        currentRoute = Route1;
    }
    case "96" : {
        currentRoute = Route96;
    }
    default:
        currentRoute = new String[0];
}

Note that your code also had a redundancy - in both declarations of the inner currentRoute you assigned it a new array, and then immediately discarded that value.

Also note that I added a default. Without a default, Java compiler would complain about currentRoute not being initialized.

Upvotes: 6

vitro
vitro

Reputation: 939

Do it like this

String[] currentRoute = null;
switch (routeID)
{
    case "1" : {
        currentRoute = Route1;
    }
    case "96" : {
        currentRoute = Route96;
    }
}

if (currentRoute != null )
    // print out values in currentRoute
    for (int i = 0; i < currentRoute.length; i++)
    {
       System.out.println(currentRoute[i]);
    }
}

Upvotes: 7

Related Questions