切换语句意外结果

时间:2012-11-11 09:17:02

标签: java switch-statement

我写了这段代码,但似乎没有用。当我们输入d时,它会对美元进行计算,但仍在进行(......什么?)。

你能在列表部分看到+ detect +,那部分是错误的吗?

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);
            } 
    }

3 个答案:

答案 0 :(得分:4)

您需要在每个案例的末尾为switch语句添加break

请参阅http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

答案 1 :(得分:2)

在每个break块中的每个系列语句的末尾添加case,例如:

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指出了一个特定于switchhere的教程,但我会退后一步,对基础知识进行一些回顾。

为此,这是一个正确编写的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;
}

答案 2 :(得分:1)

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;
}