简体   繁体   中英

How do I prevent my console app from closing until its condition is met?

I'm new to C# and this is my program. I will guess a number between 1 and 3 If my guess is correct, it'll close my console app after I press enter which is not the problem. The problem is, if i guessed incorrectly, I will guess again, after I pressed enter program closes. What is the solution, to prevent my console app closing when pressing enter after I guessed wrong? This is the code Sorry about my question..

Random rnd = new Random();
int num1 = rnd.Next(1, 3);
int num2;
Console.WriteLine("Guess my number");
num2 = int.Parse(Console.ReadLine());
if (num2 == num1)
    Console.WriteLine("Very Good!");

else
    Console.WriteLine("Guess again");

Console.ReadLine();

Wrap your code in a do...while statement. So:

do 
{
    num2 = int.parse...
    .... 
}
while (num2 != num1);
Console.ReadLine();

What this does is it keeps on executing the code in the do while loop until num2 is equal to num1, in this case when the user guesses it correctly!

Random rnd = new Random();
int num1 = rnd.Next(1, 3);
int num2;

Console.WriteLine("Guess my number");

while(true)
{  
   //NOTE, if the user entered characters other than number, the program
   //will throw an exception, you should check user input before making the parsing
   num2 = int.Parse(Console.ReadLine());

   if (num2 == num1)
   {
   Console.WriteLine("Very Good!");
   break;
   }
   else
    Console.WriteLine("Guess again");
}
Console.ReadLine();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM