End*_*Egg 6 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;
Run Code Online (Sandbox Code Playgroud)
第一个"mol"没有问题,但在案例1和案例2中,它表示"重复局部变量mol".如果我使用If语句就可以了.Java是这样还是有办法绕过它?
谢谢
Roh*_*ain 16
那是因为a 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;
}
Run Code Online (Sandbox Code Playgroud)
但是,理想情况下,不需要为每种情况声明一个单独的局部变量.如果在所有情况下都使用变量,那么这清楚地表明要在switch语句中直接声明的变量:
switch (someVar) {
double mol = 0.0;
case 0: mol = n / Na;
break;
case 1: mol = m / M;
break;
}
Run Code Online (Sandbox Code Playgroud)
PS:我能不能指点你从英文字母分开命名变量的东西- ,n,?MN