سؤال

Not Homework..So I've got a simple console program to read exam scores and prints out the average and grade. So far it's the following:

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...);

Now I want to check for invalid entries with TryParse. I thought I'd stick in another while loop before the other and change the original one like this:

 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...

The problem here is that if the user enters valid entries at first and then enters an invalid one, the compiler can't get back to the first while loop to check for the invalid entry. So I tried to swap the positions of the while loops. But this has the same effect; it can't get back to the first while loop to check for valid entries after an invalid one is entered. The answer is most likely simple, but I'm stuck.

هل كانت مفيدة؟

المحلول

The issue you are having is that you break from the first loop when the TryParse returns true, but have no recourse to re-enter the loop. Instead you should nest your loops. The loop with the sentinel should be the outer loop, and the loop that validates and re-prompts the user should be the inner loop. Here is an example:

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
  }  
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top