2017-08-15 65 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