2017-08-15 39 views
-1

我是C#的新手,並嘗試使用定點控制循環創建GPA計算器。爲了結束循環,我希望用戶輸入'x',但它會拋出異常。我很確定這是因爲'x'不是雙重類型,但我不知道如何使它工作。我之前使用一個數字退出,但它一直添加到gradeTotal。任何建議都會很棒!謝謝!C#我如何處理這個異常?

代碼:

class Program 
{ 
    static void Main(string[] args) 
    { 


     double gradeTotal = 0; 
     int[] score = new int[100]; 
     string inValue; 
     int scoreCnt = 0; 
     Console.WriteLine("When entering grades, use a 0-4 scale. Remember; 
     A = 4, B = 3, C = 2, D = 1, F = 0"); 
     Console.WriteLine("Enter grade {0}: ((X to exit)) ", scoreCnt + 1); 
     inValue = Console.ReadLine(); 
     gradeTotal += double.Parse(inValue);//This may be a problem area 
     while (inValue != "x") 
     { 
      if (int.TryParse(inValue, out score[scoreCnt]) == false) 
       Console.WriteLine("Invalid data -" + "0 stored in array"); 
      ++scoreCnt; 
      Console.WriteLine("Enter Score{0}: ((X to exit)) ", scoreCnt + 
      1); 
      inValue = Console.ReadLine(); 
      gradeTotal += double.Parse(inValue);//This is a problem area 
     } 
     Console.WriteLine("The number of scores: " + scoreCnt); 
     Console.WriteLine("Your GPA is: " + gradeTotal);//Obviously not the 
     //right calculation, just trying to figure it out 
     Console.ReadLine(); 
    } 
} 
+1

你得到什麼異常? –

+1

如果按下任何非數字鍵,則會發生這種情況。使用[Int.TryParse()](https://stackoverflow.com/questions/4804968/how-can-i-validate-console-input-as-integers),它會告訴你它是否是一個有效的整數。 (不需要雙倍數,因爲您只需要查找0到4) –

+0

請從搜索結果中選擇重複選項 - https://www.bing.com/search?q=c%23+formatexception+double –

回答

0

最少的努力

而不是

gradeTotal += double.Parse(inValue);//This is a problem area 

嘗試

if (inValue == "X") break; 
gradeTotal += double.Parse(inValue); 

更強大

double d; 
var ok = double.TryParse(inValue, out d); 
if (!ok) break; 
gradeTotal += d; 
+0

謝謝!這工作! – sandracodes

0

你必須嘗試分析它之前的inValue零驗證。那就是問題所在。你如何解決這個問題取決於你。這裏有幾個建議:

  • 包裝在一個try ... catch代碼...

    嘗試{

    grandTotal += double.Parse(inValue); 
    

    }趕上(例外五){

    Console.WriteLine("Invalid input!"); 
    

    }

  • 使用正則表達式驗證用戶輸入和返回錯誤,如果不是數字 (System.Text.RegularExpressions.Regex