簡體   English   中英

Switch語句:為什么我在不同的情況下不能擁有相同的變量名? Java的

[英]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:我可以建議你將變量命名為英文字母nMN嗎?

因為那些變量存在於single block中,您可能會在某些method編寫此switch語句。 在單個方法中,您不能擁有重復變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM