How do I create a terminable while loop in console

2020-03-30 06:05发布

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 code below but I only came up with results relating to breaking while loops or the solution to be not to put it in a while loop


        int P1Choice = int.Parse(Console.ReadLine());

        while (true)
        {
            if (P1Choice == 1)
            {
                Console.WriteLine("");
                CenterWrite("You have chosen Defult Empire 1");
                break;
            }
            if (P1Choice == 2)
            {
                Console.WriteLine("");
                CenterWrite("You have chosen Defult Empire 2");
                break;
            }
            if (P1Choice == 3)
            {
                Console.WriteLine("");
                CenterWrite("You have chosen Defult Empire 3");
                break;
            }
            if (P1Choice == 4)
            {
                Console.WriteLine("");
                CenterWrite("You have chosen Defult Empire 4");
                break;
            }
            else
            {
                Console.WriteLine("");
                CenterWrite("Input Invalid, Please press the number from the corresponding choices to try again");
                Console.ReadKey();
                int P1Choice = int.Parse(Console.ReadLine());
            }
        }

I understand that I can't declare the local parameter "P1Choice" in this scope, but then are there any other methods to achieve the output of the code in such that when the user doesn't input the corresponding choices, that it loops again?

标签: c#
7条回答
放我归山
2楼-- · 2020-03-30 06:30

I hope this is what you need. The possibles values are in the List "list" and it loops until the answer is one of the possible values:

        int value = 0;

        List<int> list = new List<int> { 1, 2, 3, 4 }; // choices are in the list

        while (true)
        {
            Console.WriteLine("Please enter a number :");
            if (int.TryParse(Console.ReadLine(), out value))
            {
                if (list.Contains(value))
                    break;
            }
        }

        // value is in the list, deal with it.
查看更多
疯言疯语
3楼-- · 2020-03-30 06:35

You have 2 problems: 1. Your code doesn't compile because you try to bind P1Choice twice. 2. You ask for input twice in your else case.

To fix 1., you have to remove int from the second occurrence of P1Choice, the one in the else case.

To fix 2., you have to remove Console.readKey() in the else case.

Besides, your code will be easier to read if you use else if clauses instead of just if clauses.

while (true) {
    int P1Choice = int.Parse(Console.ReadLine());
    if (P1Choice == 1) {
        Console.WriteLine("");
        CenterWrite("You have chosen Default Empire 1");
    } else if (P1Choice == 2) {
        Console.WriteLine("");
        CenterWrite("You have chosen Default Empire 2");
    } else if (P1Choice == 3) {
        Console.WriteLine("");
        CenterWrite("You have chosen Default Empire 3");
    } else if (P1Choice == 4) {
        Console.WriteLine("");
        CenterWrite("You have chosen Default Empire 4");
    } else {
        Console.WriteLine("");
        CenterWrite("Input Invalid, Please press the number from the corresponding choices to try again");
    }
}

Furthermore, I'd recommend you to use a switch clause instead of this many if clauses. But let that be a lecture for another day. :)

You can make further improvements. In all cases, you call Console.WriteLine("") so move it outside.

while (true) {
    int P1Choice = int.Parse(Console.ReadLine());
    Console.WriteLine("");
    if (P1Choice == 1) {
        CenterWrite("You have chosen Default Empire 1");
    } else if (P1Choice == 2) {
        CenterWrite("You have chosen Default Empire 2");
    } else if (P1Choice == 3) {
        CenterWrite("You have chosen Default Empire 3");
    } else if (P1Choice == 4) {
        CenterWrite("You have chosen Default Empire 4");
    } else {
        CenterWrite("Input Invalid, Please press the number from the corresponding choices to try again");
    }
}

Instead of having fixed Strings, you can concatenate the value of P1Choice.

while (true) {
    int P1Choice = int.Parse(Console.ReadLine());
    Console.WriteLine("");
    if (1 <= P1Choice && P1Choice <= 4) {
        CenterWrite("You have chosen Default Empire " + P1Choice);
    } else {
        CenterWrite("Input Invalid, Please press the number from the corresponding choices to try again");
    }
}
查看更多
冷血范
4楼-- · 2020-03-30 06:40

You just have to use readline inside your while loop and in else also do break. It should work this way:

 int P1Choice;

    while (true)
    {
    P1Choice = int.Parse(Console.ReadLine());

        if (P1Choice == 1)
        {
            Console.WriteLine("");
            CenterWrite("You have chosen Defult Empire 1");
            break;
        }
        if (P1Choice == 2)
        {
            Console.WriteLine("");
            CenterWrite("You have chosen Defult Empire 2");
            break;
        }
        if (P1Choice == 3)
        {
            Console.WriteLine("");
            CenterWrite("You have chosen Defult Empire 3");
            break;
        }
        if (P1Choice == 4)
        {
            Console.WriteLine("");
            CenterWrite("You have chosen Defult Empire 4");
            break;
        }
        else
        {
            Console.WriteLine("");
            CenterWrite("Input Invalid, Please press the number from the corresponding choices to try again");
    break;
        }
    }
查看更多
你好瞎i
5楼-- · 2020-03-30 06:41

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!

查看更多
家丑人穷心不美
6楼-- · 2020-03-30 06:45

One option can be to create method and keep calling until valid input comes:

public static void ProcessInput(string input)
{
    int choice = Convert.ToInt32(input);
    switch (choice)
    {
        case 1:
            Console.WriteLine("");
            Console.WriteLine("You have chosen Defult Empire 1");
            break;
        case 2:
            Console.WriteLine("");
            Console.WriteLine("You have chosen Defult Empire 2");
            break;
        case 3:
            Console.WriteLine("");
            Console.WriteLine("You have chosen Defult Empire 3");
            break;
        case 4:
            Console.WriteLine("");
            Console.WriteLine("You have chosen Defult Empire 4");
            break;
        default:
            Console.WriteLine("");
            Console.WriteLine("Input Invalid, Please press the number from the corresponding choices to try again");
            ProcessInput(Console.ReadLine());
            break;
    }

and in your main program:

public static void Main()
{
    Console.WriteLine("Hello World");
    ProcessInput(Console.ReadKey());
}
查看更多
Melony?
7楼-- · 2020-03-30 06:53

Here is code based on the post you deleted :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            BattleGrid grid = new BattleGrid();
            grid.PrintGrid();
            Console.ReadLine();
        }
    }
    public class BattleGrid
    {
        public List<List<BattleGridCell>> grid = new List<List<BattleGridCell>>();

        public BattleGrid()
        {
            for (int row = 0; row < 4; row++)
            {
                List<BattleGridCell> newRow = new List<BattleGridCell>();
                grid.Add(newRow);
                for (int col = 0; col < 4; col++)
                {
                    BattleGridCell newCell = new BattleGridCell();
                    newRow.Add(newCell);
                    newCell.rowLetter = ((char)((int)'A' + row)).ToString();
                    newCell.colnumber = col.ToString();
                }
            }
        }
        public void PrintGrid()
        {
            foreach (List<BattleGridCell> row in grid)
            {
                Console.WriteLine("|" + string.Join("|", row.Select(x => "X" + x.rowLetter + x.colnumber))); 
            }
        }
    }

    public class BattleGridCell
    {
        public string rowLetter { get; set; }
        public string colnumber { get; set; }
    }
}
查看更多
登录 后发表回答