Leonz Leonz - 5 months ago 14
Java Question

Why can't I use same variable in switch?

For example, if I write code like this:

double result = 0;
switch (operation) {
case "divide":
double result = (double) first / second;
string = Double.toString(result);
break;
case "multiply":
double result = (double) first * second;
string = Double.toString(result);
break;
case "substract":
double result = (double) first - second;
string = Double.toString(result);
break;
case "add":
double result = (double) first + second;
string = Double.toString(result);
break;
}


It returns error: Variable 'result' is already defined in the scope.

I know how to work around this. I could make a different variable in each case, but that would then prolong code by having to write code for each variable.

How to make this work as written in the code given?

Answer

This is being caused by the fact that result is already defined at the top of the switch statement, and you are declaring it again in your statement.

Try something like this:

switch (operation) {
    case "divide":
        double result = (double) first / second;
        string = Double.toString(result);
        break;
    case "multiply":
        double result = (double) first * second;
        string = Double.toString(result);
        break;
    case "substract":
        double result = (double) first - second;
        string = Double.toString(result);
        break;
    case "add":
        double result = (double) first + second;
        string = Double.toString(result);
        break;
}

In other words, what you had before, except from your initial declaration.


Alternatively, you could declare the double and use it in each of your cases:

double result = 0;
switch (operation) {
    case "divide":
        result = (double) first / second;
        string = Double.toString(result);
        break;

    ...

As Yassin Hajaj pointed out in the comments, it would be much better if you used the string = Double.toString(result); line once at the end of your switch statement, instead of repeating it multiple times.

That would look something like this:

double result = 0;
switch (operation) {
    case "divide":
        result = (double) first / second;
        break;
    case "multiply":
        result = (double) first * second;
        break;
    ...
}
string = Double.toString(result);
Comments