I still writing the code, and it doesn't make a very big difference in a project like mine, but if I was to make something bigger, it would be a pain. here it 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 "mol" has no problem, but in case 1 and case 2, it says "Duplicate local variable mol". If I use the If statement it works. Is Java just like this or there is a way around it?
Thanks
In a word, yes. Variable names only hold in the scope they're defined in, and you can use the same name in different scopes.
The switch statement can include any number of case instances. However, no two constant-expression values within the same switch statement can have the same value.
If no matching case clause is found, the program looks for the optional default clause, and if found, transfers control to that clause, executing statements following that clause. If no default clause is found, the program continues execution at the statement following the end of switch .
Although it is usually a bad idea, you can declare a formal parameter or a local variable with the same name as one of the instance variables.
That's because a case
doesn't create a scope. So, both the variables in the 2 cases are in the same scope. If you want to do this, you can add braces for each case, which will create a new scope for each 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;
}
But, ideally there is no need to declare a separate local variable for each case. If you are using a variable in all the cases, that clearly signifies that variable to be declared directly inside the switch
statement:
switch (someVar) {
double mol = 0.0;
case 0: mol = n / Na;
break;
case 1: mol = m / M;
break;
}
P.S.: Can I advice you to name your variables something apart from english alphabets - n
, M
, N
?
Because those variables are there in single block
may be you would have written this switch
statement in some method
.
In a single method you can't have dup variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With