java - Switch语句: Why can't I have the same variable name in different cases? Java

标签 java duplicates switch-statement

我仍在编写代码,对于像我这样的项目来说,这并没有太大的区别,但如果我要做更大的事情,那就会很痛苦。这是:

        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;

第一个“mol”没有问题,但是在情况1和情况2中,它显示“重复的局部变量mol”。如果我使用 If 语句它就有效。 Java 就是这样还是有办法解决它?

谢谢

最佳答案

这是因为 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.:我可以建议您将变量命名为英文字母之外的其他名称 - nMN 吗?

关于java - Switch语句: Why can't I have the same variable name in different cases? Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21953523/

相关文章:

android - GoogleCloudMessaging#register 在同一应用程序/设备中返回不同的 ID?

javascript - 如何将字符串添加到列表中而不重复

wordpress - 如何在 WordPress 中切换语言 "on-the-fly"

javascript - Jquery switch 语句偶尔会起作用

java - 将特定 bean 作为参数注入(inject)具有多个参数的函数中

java - 传入消息的监听器

java - 无法使用 Mongodb Java 驱动程序更新内部 Arraylist 对象

c# - 在 C# NET 中运行 Java 应用程序

Excel vba宏根据单元格整数值多次复制行

python - 在python中使用字典将参数传递给switch case中的函数