Sentinel控制while循环C#

时间:2013-09-27 17:47:53

标签: c# while-loop sentinel

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

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检查无效条目。我以为我会在另一个循环之前停留在另一个循环中,然后像这样改变原来的那个:

 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循环以检查有效条目。答案很可能很简单,但我被困住了。

1 个答案:

答案 0 :(得分:2)

您遇到的问题是,当TryParse返回true时,您会从第一个循环中断,但无法重新进入循环。相反,你应该嵌套你的循环。带有sentinel的循环应该是外部循环,验证并重新提示用户的循环应该是内部循环。这是一个例子:

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
  }