[英]Switch statement: Why can't I have the same variable name in different cases? Java
我仍然在編寫代碼,它在像我這樣的項目中沒有產生很大的不同,但如果我要做更大的事情,那將是一種痛苦。 這里是:
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;
}
PS:我可以建議你將變量命名為英文字母n
, M
, N
嗎?
因為那些變量存在於single block
中,您可能會在某些method
編寫此switch
語句。 在單個方法中,您不能擁有重復變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.