【问题标题】:C# nested if/else in a for loopC# 在 for 循环中嵌套 if/else
【发布时间】:2015-06-18 18:10:17
【问题描述】:

我在 for 循环中有一个嵌套的 if/else 语句来确定一个值是否对数组值有效。它返回所有值都很好,但是如果 IF 是正确的,它仍然会执行 else 额外的 3 次。我以为一旦相等,它就会停止,但我想我在这里遗漏了一些东西。

string sectionChoice;
int ticketQuantity;
double ticketPrice, totalCost;
string[] section = { "orchestra", "mezzanine", "balcony", "general" };
double[] price = { 125.25, 62.00, 35.75, 55.50 };
bool isValidSection = false;

sectionChoice = GetSection();
ticketQuantity = GetQuantity();

for (int x = 0; x < section.Length; ++x)
{
    if (sectionChoice == section[x])
    {
        isValidSection = true;
        ticketPrice = price[x];

        totalCost = CalcTicketCost(ticketPrice, ticketQuantity);
        Console.Write("\n\nTotal cost for the tickets are: {0:c2}", totalCost);
    }
    else
        Console.Write("\n\nInvalid entry, {0} does not exist", sectionChoice);
}

当它有效时,它返回如下内容:

您的价格是 32.50。无效条目,x 不存在 无效条目,x 不存在 无效条目,x 不存在

【问题讨论】:

  • 您应该使用 decimal 来表示货币值 (read more)。

标签: c# if-statement for-loop


【解决方案1】:

您真正想做的是确定section 是否包含特定值,如果包含,则执行某些操作。直接检查那个

if (section.Contains(sectionChoice))

您也不应该使用parallel arrays。而不是有两个数组,部分是价格,其中每个索引处的对象“组合”等于一个值,看起来你实际建模的是一种查找特定部分价格的方法。最好使用Dictionary 建模,它可以轻松查找特定键的值。在这里,您的关键是部分,价值是它的价格。

Dictionary<string, decimal> ticketsPrices = new Dictionary<string, decimal>()
{
    {"orchestra", 125.25m},
    //...
};
bool isValidSection = false;

string sectionChoice = GetSection();
int ticketQuantity = GetQuantity();

if (ticketsPrices.ContainsKey(sectionChoice))
{
    isValidSection = true;
    decimal ticketPrice = ticketsPrices[sectionChoice];

    decimal totalCost = CalcTicketCost(ticketPrice, ticketQuantity);
    Console.Write("\n\nTotal cost for the tickets are: {0:c2}", totalCost);
}
else
    Console.Write("\n\nInvalid entry, {0} does not exsist", sectionChoice);

【讨论】:

  • 这个答案通过识别意图并以更好的方式解决问题而超越了其他答案。
  • x 会发生什么?您仍然需要索引来获取价格,但这是正确的想法(或者字典可以与 Dictionary 一起使用)
  • @DavidSherret,说得好。一开始没看到。可以通过使用Array.IndexOf 来解决,并且仍然比其他答案更干净。
  • @DavidSherret 是的,这个设计的缺陷比我第一眼看到的还要多。这就是您避免使用并行数组的原因;它造成了巨大的混乱。
  • @adv12 解决方案是摆脱并行数组,而不是试图绕过它们。他们只会在未来继续采取行动。
【解决方案2】:

您要查找的关键字是break;

break 将停止执行它所在的循环。如果你在嵌套循环中,它只会在最里面起作用。

与此相反的是continueContinue 停止该迭代并进入下一个迭代。

Here is an MSDN article explaining it more in depth

for (int x = 0; x < section.Length; ++x)
{
   if (sectionChoice == section[x])
   {
      isValidSection = true;
      ticketPrice = price[x];

      totalCost = CalcTicketCost(ticketPrice, ticketQuantity);
      Console.Write("\n\nTotal cost for the tickets are: {0:c2}", totalCost);
      break;
   }
   else
     Console.Write("\n\nInvalid entry, {0} does not exsist", sectionChoice);
 }

【讨论】:

  • 噢!谢谢你:)
  • @JeffreyDilley 如果这对您有用,请不要忘记单击复选标记将其选为答案。
  • 当然。它说我必须等几分钟,但我肯定会的。
  • 如果所选部分不是第一个,您仍然可能会多次收到无效条目消息!
  • @OlivierJacot-Descombes 问题是如何打破循环。不要修复它背后的逻辑。让他通过反复试验来学习。
【解决方案3】:

像这样获取所选项目的索引:

int i = section.IndexOf(sectionChoice);
if (i >= 0) {
    ticketPrice = price[i];
} else {
    // Not found!
}

但是,您的代码使用项目类会变得更加灵活

public class Section
{
    public string Name { get; set; }
    public decimal Price { get; set; }
}

通过这个类,您可以创建一个像这样的部分列表

List<Item> sections = new List<item> {
    new Section { Name = "orchestra", Price = 125.25 },
    new Section { Name = "mezzanine", Price = 62.00 },
    ...
};

现在你可以找到这样的部分:

Section section = sections.FirstOrDefault(s => s.Name == sectionChoice);
if (section != null ) ...

这样更容易向部分添加新属性。例如。您可以向其中添加一些剩余席位,而无需创建新数组。

【讨论】:

    【解决方案4】:

    您不想报告它对于每个不匹配的选项都是无效的选择:

    for (int x = 0; x < section.Length; ++x)
    {
        if (sectionChoice == section[x])
        {
            isValidSection = true;
            ticketPrice = price[x];
    
            totalCost = CalcTicketCost(ticketPrice, ticketQuantity);
            Console.Write("\n\nTotal cost for the tickets are: {0:c2}", totalCost);
            break;
         }
    }
    
    if (!isValidSection)
        Console.Write("\n\nInvalid entry, {0} does not exist", sectionChoice);
    

    【讨论】:

    • 我可以请求否决票的原因吗?这只是我的第三篇文章。我不确定它缺少的地方。
    • 其实无效入口消息必须放在循环之后,否则还是有可能多次写入控制台!
    【解决方案5】:

    如果您希望在满足if 条件时停止迭代,您需要使用break 语句跳出循环:

    for (int x = 0; x < section.Length; ++x)
    {
    
        if (sectionChoice == section[x])
        {
            isValidSection = true;
            ticketPrice = price[x];
    
            totalCost = CalcTicketCost(ticketPrice, ticketQuantity);
            Console.Write("\n\nTotal cost for the tickets are: {0:c2}", totalCost);
            break;  // THIS IS THE IMPORTANT CHANGE
        }
    
    }
    if (!isValidSection) // TEST MOVED OUTSIDE OF LOOP
    {
        Console.Write("\n\nInvalid entry, {0} does not exsist", sectionChoice);
    }
    

    【讨论】:

    • 如果所选部分不是第一个,您仍然可能会多次收到无效条目消息!
    猜你喜欢
    • 1970-01-01
    • 2018-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 2018-04-02
    相关资源
    最近更新 更多