0

我写了这段代码,但它似乎不起作用。当我们输入d时,它会计算美元,但仍然在做(..what?)。

你能看到列表部分中的+检测+,错误的部分吗?

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

3 回答 3

4

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

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

于 2012-11-11T09:21:13.410 回答
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 指出了一个特定于这里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;
}
于 2012-11-11T09:28:14.950 回答
1

beak正如 Omar Jackman 已经指出的那样,缺少必要的关键字。此外,要处理无效输入('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;
}
于 2012-11-11T09:33:11.260 回答