C#如何处理此异常?

时间:2017-08-15 18:16:16

标签: c#

我是C#的新手,并尝试使用哨兵控制循环创建GPA计算器。要结束循环,我希望用户输入'x',但它会抛出异常。我很确定这是因为'x'不是双重类型,但我不确定如何才能使它工作。我之前使用的是一个号码,但它仍然被添加到gradeTotal中。任何建议都会很棒!谢谢!

代码:

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();
    }
}

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

在尝试解析之前,您对inValue没有验证。那就是问题所在。你如何解决这个问题取决于你。以下是一些建议:

  • 将代码包装在try ... catch ...

    尝试{

     grandTotal += double.Parse(inValue);
    

    } catch(例外e){

     Console.WriteLine("Invalid input!");
    

    }

  • 使用正则表达式验证用户输入,如果不是数字则返回错误 (System.Text.RegularExpressions.Regex