How do I create a terminable while loop in console application?

前端 未结 7 1867
情话喂你
情话喂你 2021-01-16 04:41

I am currently looking for a solution for this c# console application function

I tried searching for a method for creating a while loop that can terminate for the co

7条回答
  •  温柔的废话
    2021-01-16 05:23

    If you want to exit a while loop only when certain statements are met, then that's what you should state when entering your loop.

    I would use a boolean to know whether the user made a right choice or not.

    bool right_choice = false;
    int P1Choice = int.Parse(Console.ReadLine());
    while(!right_choice) {
        switch(P1Choice) {
            case 1: 
                 right_choice = true;
                 {case 1 code};
                 break;
            case 2:
                 right_choice = true;
                 {case 2 code};
                 break;
            case 3:
                 right_choice = true;
                 {case 3 code};
                 break;
            case 4:
                 right_choice = true;
                 {case 4 code};
                 break;
             default:
                 break;
        }
        if (!right_choice) {
            Console.WriteLine("");
            CenterWrite("Input Invalid, Please press the number from the corresponding choices to try again");
            Console.ReadKey();
            P1Choice = int.Parse(Console.ReadLine());
        }    
      }    
    }
    

    This way as soon as the user makes a correct choice you exit the loop. Note that I changed your code to use a switch case instead of 4 ifs, since this would be the accepted way of implementing user input choice.

    Good luck!

提交回复
热议问题