【问题标题】:Changing an if else statement to a switch statement将 if else 语句更改为 switch 语句
【发布时间】:2014-10-15 20:35:26
【问题描述】:

我想知道将 do while 循环中的 if 语句转换为 do while 循环中的 switch 语句的最佳方法是什么。

收紧此代码的更好方法是什么?

    do{


        currency = keyboard.nextInt();

        if (currency == 1)
        {
            sterling = euros * 0.79;
            System.out.printf("£ %.2f", sterling);
        }
        else if (currency == 2)
        {
            usDollars = euros * 1.28;
            System.out.printf("$ %.2f", usDollars);
        }
        else if (currency == 3){
            auDollars = euros * 1.44;
            System.out.printf("$ %.2f", auDollars);
        }
        else{
            System.out.printf("Invalid Option");
        }


        System.out.printf("\nWould you like to go again");
        System.out.printf("\n1. Yes\n2  No");
        repeat = keyboard.nextInt();

        if (repeat ==  2){
            System.out.printf("Exit Program");
            System.exit(0);
        }
    }while(repeat == 1);

【问题讨论】:

  • 你为什么不去read up on switch statements,自己试试,然后问你有没有问题?听起来您是在要求我们为您做这件事。
  • “在 do while loo 中转换此 if 语句的最佳方式”。我希望你知道 loo 的含义。您在发布问题之前阅读过您的问题吗?

标签: java switch-statement do-while


【解决方案1】:

对于您的示例,if 语句和 switch 将执行完全相同的操作。没有差异。 你可以从你的代码中改变的是最后一个 if 语句:

if (repeat ==  2){
   System.out.printf("Exit Program");
   System.exit(0);
}

你可以在do while之外写这个if语句,这样只会检查一次。

【讨论】:

  • 这会破坏他的程序,更不用说这甚至不能回答问题。
  • do while 正在检查 repeat 的值。如果值为 1 将退出,如果它等于 2,则可以在外部进行检查。像这样他有它,重复值在 do while 中被检查两次。
  • 我回答了这个问题。我只是给了一个额外的提示。
  • 啊,我的错。我误读了while条件。不过,这并不能回答问题。 OP 询问如何将他的if 语句转换为switch。不过,请不要只为他做这件事——这个问题应该仍然没有答案,IMO。
【解决方案2】:

开关盒看起来像这样

 switch (currency) {
            case 1:  System.out.printf("£ %.2f", euros * 0.79);
                     break;
            case 2: . 
                    .
                    .
                    .
                    .
                    .
                    .
            case n: . 
                     break;
            default: System.out.printf("Invalid Option");
                     break;
            }

即使在循环中也没有什么不同(for、while、do while)

阅读有关Switch 语句的更多信息并尝试自己完成代码

附带说明,无需创建变量 (sterling,usDollars,auDollars) 来存储表达式 euros * 0.79 的值,除非您使用存储以供以后使用,这似乎没有就这样吧。

【讨论】:

    【解决方案3】:

    您可以将转换率放在一个数组中,然后使用本来应该是 switch/if 变量来索引该数组。比如:

                float[] rates = {0.79f, 1.28f, 1.44f};
    
                answer = euros * rates[currency-1];
                System.out.printf("$ %.2f", answer);
    


    那么你就不需要选择语句了。一般来说,如果您看到大量结构重复,请查找通用代码并尝试将其排除。

    【讨论】: