【问题标题】:How to loop an if-statement with many else if conditions如何使用许多其他 if 条件循环 if 语句
【发布时间】:2015-09-28 00:43:54
【问题描述】:

在我的代码中循环 if 语句时遇到问题。我查看了 stackoverflow 上的其他线程,但我无法让它多次工作。我正在尝试创建的程序是铸造公司的基本转换器。我试图做的是让用户可以输入所需的转换类型,然后输入蜡的重量。然后它将为用户提供正确数量的贵金属克数以供使用。问题是我需要它从头开始运行,直到用户完成使用它。我尝试使用 while 语句,但它只是循环 if 语句的 else 部分。这是我的代码供参考:

static void Main(string[] args)
    {
        double waxWeight, bronzeWeight, silverWeight, fourteenkGoldWeight,
            eighteenkGoldWeight, twentytwokGoldWeight, platinumWeight;
        string wW;

        bool doesUserWantToLeave = false;

        Console.WriteLine("Please specify the type of conversion you would like to accomplish:" 
            + "\n(Bronze, Silver, 14k Gold, 18k Gold, 22k Gold, Platinum, or Exit):");

        string conversionType = Console.ReadLine();

        //bool B = conversionType == "Bronze";
        //bool S = conversionType == "Silver";
        //bool ftG = conversionType == "14k Gold";
        //bool etG = conversionType == "18k Gold";
        //bool ttG = conversionType == "22k Gold";
        //bool P = conversionType == "Platinum";

        while (!doesUserWantToLeave)
        {

            if (conversionType == "Bronze")
            {
                Console.WriteLine("What is the weight of the wax model?");
                wW = Console.ReadLine();
                waxWeight = double.Parse(wW);

                bronzeWeight = waxWeight * 10;
                Console.WriteLine("You need " + bronzeWeight + " grams of bronze.");
                Console.ReadLine();
            }

            else if (conversionType == "Silver")
            {
                Console.WriteLine("What is the weight of the wax model?");
                wW = Console.ReadLine();
                waxWeight = double.Parse(wW);

                silverWeight = waxWeight * 10.5;
                Console.WriteLine("You need " + silverWeight + " grams of silver.");
                Console.ReadLine();
            }

            else if (conversionType == "14k Gold")
            {
                Console.WriteLine("What is the weight of the wax model?");
                wW = Console.ReadLine();
                waxWeight = double.Parse(wW);

                fourteenkGoldWeight = waxWeight * 13.5;
                Console.WriteLine("You need " + fourteenkGoldWeight + " grams of 14 Karat gold.");
                Console.ReadLine();
            }

            else if (conversionType == "18k Gold")
            {
                Console.WriteLine("What is the weight of the wax model?");
                wW = Console.ReadLine();
                waxWeight = double.Parse(wW);

                eighteenkGoldWeight = waxWeight * 15;
                Console.WriteLine("You need " + eighteenkGoldWeight + " grams of 18 Karat gold.");
                Console.ReadLine();
            }

            else if (conversionType == "22k Gold")
            {
                Console.WriteLine("What is the weight of the wax model?");
                wW = Console.ReadLine();
                waxWeight = double.Parse(wW);

                twentytwokGoldWeight = waxWeight * 17.3;
                Console.WriteLine("You need " + twentytwokGoldWeight + " grams of 22 Karat gold.");
                Console.ReadLine();
            }

            else if (conversionType == "Platinum")
            {
                Console.WriteLine("What is the weight of the wax model?");
                wW = Console.ReadLine();
                waxWeight = double.Parse(wW);

                platinumWeight = waxWeight * 21.5;
                Console.WriteLine("You need " + platinumWeight + " grams of platinum.");
                Console.ReadLine();
            }

            else if (conversionType == "Exit")
            {
                doesUserWantToLeave = true;
            }

            else
            {
                Console.WriteLine("Sorry! That was an invalid option!");
                Console.ReadLine();
            }
        }
    }

我意识到一个好的程序员不会两次输入相同的代码,但我还没有达到那个水平,我只是想让代码循环。我是否必须使它成为一个大的嵌套 if 语句?

【问题讨论】:

  • 其实我有点嫉妒这个问题似乎很容易获得三票。
  • @UweKeim 好吧,看到答案了……令人难以置信的是,这么多人完全错过了这么简单的问题和这么简单的代码段的重点。

标签: c# loops if-statement


【解决方案1】:

您只需要一次金属类型。在while 循环内移动提示并接收用户输入的两行:

while (!doesUserWantToLeave)
{
    Console.WriteLine("Please specify the type of conversion you would like to accomplish:" 
        + "\n(Bronze, Silver, 14k Gold, 18k Gold, 22k Gold, Platinum, or Exit):");

    string conversionType = Console.ReadLine();


    if (conversionType == "Bronze")
    {
...

您提到您是编程新手,并且意识到您在重复自己。不过,您正确地优先考虑让代码首先工作。这很好。让它工作后,您应该考虑改进代码。

首先,在每个if 之后重复以下三行,因此只需要在循环顶部询问一次:

Console.WriteLine("What is the weight of the wax model?");
wW = Console.ReadLine();
waxWeight = double.Parse(wW);

接下来,每个if 的最后两行大部分重复,但唯一改变的部分(金属名称)是已知的。所以它们都可以在循环结束时被删除并替换为一个副本:

Console.WriteLine("You need " + metalWeight + " grams of {0}.", 
                  conversionType.ToLower());
Console.ReadLine();

然后每个if 只留下一行。它也会重复,所需的值可以存储在 Dictionary 中。完成所有这些,您最终可能会得到如下解决方案:

static void Main(string[] args)
{
    bool userWantsToStay = true;
    var conversions = new Dictionary<string, double>
    {
        { "Bronze", 10.0 },
        { "Silver", 10.5 },
        { "14k Gold", 13.5 },
        { "18k Gold", 15.0 },
        { "22k Gold", 17.3 },
        { "Platinum", 21.5 }
    };

    while (userWantsToStay)
    {
        Console.WriteLine("Please specify the type of conversion you would like to accomplish:");
        Console.WriteLine("(Bronze, Silver, 14k Gold, 18k Gold, 22k Gold, Platinum, or Exit):");
        var metalType = Console.ReadLine();

        Console.WriteLine("What is the weight of the wax model?");
        var wW = Console.ReadLine();
        var waxWeight = double.Parse(wW);

        if (conversions.ContainsKey(metalType))
        {
            var metalWeight = waxWeight * conversions[metalType];
            Console.WriteLine("You need {0} grams of {1}.", metalWeight, metalType.ToLower());
            Console.ReadLine();
        }
        else if (metalType == "Exit")
        {
            userWantsToStay = false;
        }
        else
        {
            Console.WriteLine("Sorry! That was an invalid option! Try again");
            Console.ReadLine();
        }
    }
}

这可以进一步改进(许多ReadLines 可能会被删除;您没有在解析之前测试权重输入是否是有效的双精度数),但它会让您走上正确的道路。

【讨论】:

  • 我真的很想为You correctly prioritise getting the code working first though. 给你超过 +1 的回答:)
【解决方案2】:

你必须在循环结束时重新分配用户选项,否则它永远不会改变:

while (!doesUserWantToLeave)
{
    if (conversionType == "Bronze")
    {
        //....
    }
    // ...
    else if (conversionType == "Exit")
    {
        doesUserWantToLeave = true;
    }
    else
    {
        Console.WriteLine("Sorry! That was an invalid option!");
    }
    conversionType = Console.ReadLine();
}

因此,您还必须删除循环中的所有其他 Console.ReadLine();。您也可以使用break 代替doesUserWantToLeave = true,这样会退出循环。

【讨论】:

    【解决方案3】:

    您可以将这段代码提取到一个单独的方法中,该方法将从主程序的循环中调用,请参见下面的伪代码:

    public void Main(string[] args)
    {
       while(!doesUserWantToLeave) {
          Console.WriteLine("Please specify the type of conversion you would like to accomplish:" 
          + "\n(Bronze, Silver, 14k Gold, 18k Gold, 22k Gold, Platinum, or Exit):");
          string conversionType = Console.ReadLine();
    
          Console.WriteLine("What is the weight of the wax model?");
          double waxWeight = double.Parse(Console.ReadLine());
    
          double weight = ConvertMethod(conversionType, waxWeight);
    
          Console.WriteLine(string.Format("You need {0} grams of {1}.", weight, conversionType));
       }
    }
    

    该方法如下所示。可以传递字符串,也可以使用枚举来定义转换类型。

    public double ConvertMethod(string type, double weight)
    {
       switch(type) {
          case "Silver":
             return weight * 10.5;
          case "Bronze":
             return weight * 10;
    
         // etc...
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-27
      • 2022-11-26
      • 1970-01-01
      • 1970-01-01
      • 2018-10-09
      • 2018-07-02
      • 2019-10-22
      相关资源
      最近更新 更多