我是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();
}
}
你得到什麼異常? –
如果按下任何非數字鍵,則會發生這種情況。使用[Int.TryParse()](https://stackoverflow.com/questions/4804968/how-can-i-validate-console-input-as-integers),它會告訴你它是否是一個有效的整數。 (不需要雙倍數,因爲您只需要查找0到4) –
請從搜索結果中選擇重複選項 - https://www.bing.com/search?q=c%23+formatexception+double –