如何循环一个带有多个else if条件的if语句

6

我有一个问题,就是我的代码中的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 语句吗?

3
其实,我有点嫉妒这个问题似乎很容易就能得到三个赞。 - Uwe Keim
1
@UweKeim 嗯,看到这些答案...很难想象有这么多人在一个如此简单的问题和一小段代码上完全没有理解重点。 - Luaan
3个回答

5

你只需要一次询问金属类型。将提示和接收用户输入的两行代码移动到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只需要一行。它也会重复自己,所需的值可以存储在字典中。完成这些步骤,你可能会得到以下解决方案:

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可能可以被移除;在解析之前,你没有测试重量输入是否是有效的double类型),但它会让你走上正确的道路。


我真的很想给你超过+1的赞,因为“你正确地优先考虑了先让代码正常工作”。非常好的回答 :) - Luaan

3

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

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来退出循环。

-1
你可以将这段代码提取到一个单独的方法中,然后从主程序的循环中调用它,参见下面的伪代码:
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...
   }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接