0

不是家庭作业..所以我有一个简单的控制台程序来读取考试成绩并打印出平均成绩和成绩。到目前为止,情况如下:

public static void Main ()
    {
        int sum = 0;
        int count = 0;
        double average = 0;

        Console.WriteLine ("Enter all your exam scores one by one. When finished, enter -99");

        string scores = Console.ReadLine ();

        while (scores != "-99") {
            sum += int.Parse (scores);
            count++;
            scores = Console.ReadLine ();

        } 
        if (scores == "-99") {
            average = sum / count;
            if (average >= 90)
                Console.WriteLine ("Your average score is {0}. This is good for a letter grade of A", average);
                Console.WriteLine(....more scores etc...);

现在我想用 TryParse 检查无效条目。我想我会在另一个之前坚持另一个while循环并像这样改变原来的循环:

 Console.WriteLine ("Enter all your exam scores one by one. When finished, enter -99");

        string scores = Console.ReadLine ();

          while (int.TryParse(scores, out numbers) == false){
               Console.WriteLine("Please enter a valid integer")
               scores = Console.ReadLine();
               sum += int.Parse(scores);
               count++;

        } 
          while (scores != "-99" && int.TryParse(scores, out numbers) == true) {
            sum += int.Parse (scores);
            count++;
            scores = Console.ReadLine ();

        } 
          if (scores == "-99") {
            average = sum / count;
            if (average >= 90)
                Console.WriteLine ("Your average score is {0}. This is good for a letter grade of A", average); ...etc...

这里的问题是,如果用户先输入有效条目,然后输入无效条目,则编译器无法返回第一个 while 循环来检查无效条目。所以我尝试交换 while 循环的位置。但这具有相同的效果;在输入无效条目后,它无法返回第一个 while 循环来检查有效条目。答案很可能很简单,但我被困住了。

4

1 回答 1

3

您遇到的问题是您在TryParse返回时从第一个循环中断true,但没有办法重新进入循环。相反,您应该嵌套循环。带有标记的循环应该是外循环,验证和重新提示用户的循环应该是内循环。这是一个例子:

while(scores != "-99")
{
    scores = Console.ReadLine();

     while((int.TryParse(scores, out numbers) == false)
     {
        //validation failed, re-prompt user for better number
        Console.WriteLine("Bad value, try again")
        scores = Console.ReadLine()
     }

     //do stuff here with the valid score value
  }  
于 2013-09-27T18:00:24.647 回答