【问题标题】:C# How can I handle this exception?C#如何处理这个异常?
【发布时间】:2018-01-23 17:40:21
【问题描述】:

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

【问题讨论】:

  • 你遇到了什么异常?
  • 如果按下任何非数字键就会发生这种情况。改用Int.TryParse(),它会告诉你它是否是一个有效的整数。 (不需要双精度,因为您只需要 0 到 4)
  • 请从搜索结果中选择您选择的副本 - bing.com/search?q=c%23+formatexception+double
  • 即使我使用 int.TryParse() 我得到“在 mscorlib.dll 中发生类型为 'System.FormatException' 的未处理异常附加信息:输入字符串的格式不正确。”跨度>

标签: c#


【解决方案1】:

最少的努力

代替

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;

【讨论】:

    【解决方案2】:

    在尝试解析它之前,您对 inValue 的验证为零。那就是问题所在。你如何解决这个问题取决于你。这里有几个建议:

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

      试试{

       grandTotal += double.Parse(inValue);
      

      } 捕捉(异常 e){

       Console.WriteLine("Invalid input!");
      

      }

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-12
      • 1970-01-01
      • 2011-09-21
      • 1970-01-01
      • 2020-09-01
      • 2021-04-01
      • 2020-01-29
      相关资源
      最近更新 更多