2017-04-08 108 views
-2

当我输入“done”时,它不会添加数字并显示结果。它只是跳过“catch”语句的“if”语句。我已经尝试将“if”语句放在不同的地方,但是我不能这样做,因为“结果”在“try”语句中。请帮忙。 它应该是这样的:当我输入数字(5),然后“输入”,然后再输入一个数字(5.3),然后再次输入,它应该显示结果应该是“10.3”(5 + 5.3 = 10.3)。真的很抱歉,很长的文字,我感谢任何帮助。C#中,我的代码跳过了我的if语句在try-catch语句中

 while (true) 
     { 

      Console.WriteLine("Enter a number or type \"done\" to see the average: "); 
      var input = Console.ReadLine(); 

      try 
      { 
       var result = double.Parse(input); 
       if(input == "done") 
       { 
        Console.WriteLine(result += result); 
        break; 
       } 
       else 
       { 
         continue; 
       } 
      } 
      catch (FormatException) 
      { 
       Console.WriteLine("That is not valid input."); 
      } 
+1

如果它从不碰到if语句,那么它之前的某个东西正在引发异常,这是被捕获的。如果输入是“完成”的,那么你如何期待它成为双精度? –

+0

您尝试将输入解析为双_before_检查它是否等于“完成”。这意味着如果用户输入“完成”,你有一个例外,因此,如果将永远不会执行 –

回答

1

你的代码不正确:"done"没有机会解析double。你必须检查"done"第一

// since you want to aggregate within the loop, you have to declare sum 
    // without the loop 
    double sum = 0.0; 

    while (true) 
    { 
     //DONE: You're summing up, right? It'll be sum, not average 
     Console.WriteLine("Enter a number or type \"done\" to see the sum: "); 

     var input = Console.ReadLine(); 

     if (input == "done") 
     { 
      Console.WriteLine(sum); 
      break; 
     } 

     try 
     { 
      sum += double.Parse(input); 
     } 
     catch (FormatException) 
     { 
      Console.WriteLine("That is not valid input."); 
     } 
    } 
+0

非常感谢你的帮助!我是新来的,在C#中自学,这就是为什么我问这样一个愚蠢的问题。我明白我现在做错了什么。谢谢 :) –

0

你解析“完成”双数据类型,这就是为什么出现FormatException提高。