简体   繁体   中英

C#: After running program and the input is answered with an if statement, how do i get the program to keep asking the question?

I asked a question in the WriteLine form that requires a numbered input, converted it to an int, used that int in an if-else, and I want the question to be re-asked afterward. Any idea?

Example:

Console.WriteLine("What hour is it?: ");
int hour = Convert.ToInt32(Console.ReadLine());

if (hour > 0 && hour < 12)
{
    Console.WriteLine("It's morning.");
}

if (hour > 12 && hour < 18)
{
    Console.WriteLine("It's evening.");
}
else if (hour > 18 && hour < 24)
{
    Console.WriteLine("It's night.");
}
else
{
    Console.WriteLine("Invalid Input.");
}

There are three primary ways to loop in C#

  • while ( someCond is true or false)
  • for ( int someVar is 0 and it's less than or greater than or equal to some var)
  • foreach (someObj in someObjects)

Your code is as follows, in pseudocode.

  • While the user is doing something
  • Ask a question
  • Record the answer
  • Compare it to your possible conditions
  • Output a response.

Notice a key-word there in your pseudo-code. Make use of that. When learning it's imperative to take the time to understand every little tiny detail and writing it out in plain language will help you to identify those key-words.

Code Snippet

bool someBool = false;
while(!someBool)
{
    //Ask A question
    //Record an answer.
    //Check Condition
    if (true)
       {
           //Do something
           someBool = true;
       }
    else 
       {
           //Do something else.
           //Keep `someBool` set to false
       }
}

Now it's up to you to implement your code where it goes to make it function exactly how you want it to function, your conditionals, where it breaks, etc.

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