while (Boolean-expression) embedded-statement
Using the number-guessing example from earlier in the chapter, we could rewrite the example, as beginning with a while statement such that you could continue the game until you either guessed the correct number or decided to quit.
using System; class WhileApp { const int MIN = 1; const int MAX = 10; const string QUIT_CHAR = "Q"; public static void Main() { Random rnd = new Random(); double correctNumber; string inputString; int userGuess; bool correctGuess = false; bool userQuit = false; while (!correctGuess && !userQuit) { correctNumber = rnd.NextDouble() * MAX; correctNumber = Math.Round(correctNumber); Console.Write ("Guess a number between {0} and {1}...({2} to quit)", MIN, MAX, QUIT_CHAR); inputString = Console.ReadLine(); if (0 == string.Compare(inputString, QUIT_CHAR, true)) userQuit = true; else { userGuess = inputString.ToInt32(); correctGuess = (userGuess == correctNumber); Console.WriteLine ("The correct number was {0}\n", correctNumber); } } if (correctGuess && !userQuit) { Console.WriteLine("Congratulations!"); } else { Console.WriteLine("Maybe next time!"); } } }
Coding and running this application will result in output similar to the following: -
C:\>WhileApp Guess a number between 1 and 10...(Q to quit)3 The correct number was 5 Guess a number between 1 and 10...(Q to quit)5 The correct number was 5 Congratulations! C:\>WhileApp Guess a number between 1 and 10...(Q to quit)q Maybe next time!
by
updated