Switch statement: Why can't I have the same variable name in different cases? Java

I am still writing code, and it doesn’t affect the project very much like mine, but if I did something more, it would be a pain. there he is:

        case 0:
            System.out.print("Insert the N: ");
            double N = in.nextDouble();
            double mol = N / Na;
            System.out.print("There are " + mol + " mol in that sample");
            break;

        case 1:
            System.out.print("Insert the m: ");
            double m = in.nextDouble();
            System.out.print("Insert the M: ");
            double M = in.nextDouble();
            double mol = m / M;
            System.out.print("There are " + mol + " mol in that sample");
            break;

        case 2:
            System.out.print("Insert the V: ");
            double V = in.nextDouble();
            double mol = V / Vm;
            System.out.print("There are " + mol + " mol in that sample");
            break;

The first mole has no problem, but in cases 1 and 2, it says “Duplicate a local variable mole”. If I use the If statement, it works. Is Java like this, or is there a way around it?

thank

+3
source share
2 answers

, case . , . , , .

    case 0: {
        System.out.print("Insert the N: ");
        double N = in.nextDouble();
        double mol = N / Na;
        System.out.print("There are " + mol + " mol in that sample");
        break; 
    }

    case 1: {
        System.out.print("Insert the m: ");
        double m = in.nextDouble();
        System.out.print("Insert the M: ");
        double M = in.nextDouble();
        double mol = m / M;
        System.out.print("There are " + mol + " mol in that sample");
        break;
    }

. , , , ​​ switch:

switch (someVar) {
    double mol = 0.0;

    case 0: mol = n / Na;
            break;

    case 1: mol = m / M;
            break;
}

P.S.: - - n, M, n?

+13

single block, , switch method. dup.

+4

All Articles