2017-04-08 191 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提高。