簡體   English   中英

切換語句意外結果

[英]Switch statement unexpected result

我寫了這段代碼,但是似乎沒有用。 當我們輸入d ,它會為美元進行計算,但仍在執行(..什么?)。

您能在列表部分看到+檢測+嗎,那是錯誤的部分?

String currency = sc.next();
        char detect = currency.charAt(0);
switch (detect){
    case 'D':
    case 'd':
        double dollar = (amount/18*10);
        System.out.println(amount + " Turkish Lira(s) --> " + dollar + " Dollar");

    case 'E':
    case 'e':
        double euro = (amount/23*10);
        System.out.println(amount + " --> " + euro + " Euro");

    case 'T':
    case 't':
        double lira = (amount);
        System.out.println(amount + " --> " + lira+ " Lira(s)");

        while (detect!='d'|| detect!='e' || detect!='t' || detect!='D'|| detect!='E' || detect!='T'){
            System.out.println("Can u See " + detect + " In The List ?\n" + menucur);
            currency = sc.next();
            detect = currency.charAt(0);
            } 
    }

您需要在每種情況下為switch語句添加break

參見http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

在每個case塊的每個語句系列的末尾添加一個break ,例如:

switch (detect){
    case 'D':
    case 'd':
        double dollar = (amount/18*10);
        System.out.println(amount + " Turkish Lira(s) --> " + dollar + " Dollar");
        break; // <==== Add this

    case 'E':
    case 'e':
        double euro = (amount/23*10);
        System.out.println(amount + " --> " + euro + " Euro");
        break; // <==== Again here

...等等。 這告訴您您不想繼續進行下一個case

我建議閱讀Java入門。 在評論,MadProgrammer指出,具體到一個教程switch在這里 ,但我會退后一步,並做一些基本的審查。

為此,下面是正確編寫的switch語句的示例:

// Assume `n` is an integer
switch (n) {
    case 0:
    case 1:
        System.out.println("n is 0 or 1");
        break;

    case 2:
    case 3:
    case 4:
        System.out.println("n is 2, 3, or 4");
        break;

    case 17:
        System.out.println("n is 17");
        break;

    default:
        System.out.println("n has some value other than 0, 1, 2, 3, 4, or 17");
        break;
}

Omar Jackman已經指出,缺少必要的beak關鍵字。 另外,要處理無效的輸入(“ D”,“ d”,“ E”,“ e”,“ T”和“ t”以外的字母,請使用關鍵字default ):

switch(case)
    case 'D':
    case 'd': 
         double dollar = (amount/18*10);
         System.out.println(amount + " Turkish Lira(s) --> " + dollar + " Dollar");
         break;

    case 'E':
    case 'e':
         double euro = (amount/23*10);
         System.out.println(amount + " --> " + euro + " Euro")
         break;

    //.. rest of your code
    // finally:

    default: // <- handle invalid letter input
         System.out.println("Invalid input");
         break;
}

暫無
暫無

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

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