我是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 –