我仍在编写代码,对于像我这样的项目来说,这并没有太大的区别,但如果我要做更大的事情,那就会很痛苦。这是:
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.:我可以建议您将变量命名为英文字母之外的其他名称 - n
、M
、N
吗?
关于java - Switch语句: Why can't I have the same variable name in different cases? Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21953523/