开发者

Which loop do I use to ask if a user wants to continue the program in C#

开发者 https://www.devze.com 2022-12-22 04:24 出处:网络
I made a program that asks for input and returns a value. After, I want to ask if the user wants to continue. But I do开发者_如何学JAVAn\'t know what to use.You want to use a do / while loop, or an in

I made a program that asks for input and returns a value. After, I want to ask if the user wants to continue. But I do开发者_如何学JAVAn't know what to use.


You want to use a do / while loop, or an infinite while loop with a conditional break.


A do-while loop is often used:

bool @continue = false;
do
{
    //get value
    @continue = //ask user if they want to continue
}while(@continue);

The loop will be executed once before the loop condition is evaluated.


This only allows 2 keys (Y and N):

ConsoleKeyInfo keyInfo;
do {
    // do you work here
    Console.WriteLine("Press Y to continue, N to abort");

    do {
        keyInfo = Console.ReadKey();
    } while (keyInfo.Key != ConsoleKey.N || keyInfo.Key != ConsoleKey.Y);
} while (keyInfo.Key != ConsoleKey.N);


I would use a do..while loop:

bool shouldContinue;
do {
    // get input
    // do operation
    // ask user to continue
    if ( Console.ReadLine() == "y" ) {
        shouldContinue = true;
    }
} while (shouldContinue);


You probably want a while loop here, something like:

bool doMore= true;

while(doMore) {
  //Do work
  //Prompt user, if they refuse, doMore=false;
}


use Do While Loop. something similar will work

int input=0;
do
{  
  System.Console.WriteLine(Calculate(input)); 
  input =  GetUserInput();
} while (input != null)


Technically speaking, any loop will do it, a for loop for example (which is another way to write a while(true){;} )

    for (; true; )
    {
        //Do stuff
        if (Console.ReadLine() == "quit")
            {
            break;
        }
        Console.WriteLine("I am doing stuff");
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消