简体   繁体   中英

Ways to avoid crashes when using user input (int) as a link for several functions?

I can't find a clear answer on how to assign user input to be usable elsewhere as an integer without crashing the program from invalid key inputs. I'm also unsure if setting the input to be an integer is a good idea as it's the only method I know. Here's the code:

int atkchoice = Convert.ToInt32 (Console.ReadLine());

Here is how I'd like to use the input as an integer:

if (atkchoice == 1)
                {

If you use Convert.ToInt32(), you might get an exception if the input is not a number. Using TryParse() method is more safe.

int atkchoice;
do
{
    // repeat until input is a number
    Console.WriteLine("Please input a number! ");
} while (!int.TryParse(Console.ReadLine(), out atkchoice));

Console.WriteLine("You entered {0}", atkchoice);

If you want to validate that input is in a set of numbers, you can create an enumeration of user choice then check if the input is correct. Use Enum.IsDefined to validate the value is in the enumeration.

enum UserChoiceEnum
{
    Choice1 = 1,
    Choice2,
    Choice3
}

void Main()
{
    int atkchoice;
    do
    {
        do
        {
            // repeat until input is a number
            Console.WriteLine("Please input a number! ");
        } while (!int.TryParse(Console.ReadLine(), out atkchoice));
    } while (!Enum.IsDefined(typeof(UserChoiceEnum), atkchoice));

    Console.WriteLine("You entered {0}", atkchoice);
}

Please refer to this(link to another similar question in stackoverflow) C# char to int . I guess it will answer most of your queries..(for your comment above - "Thank you this works perfectly but now I'm curious if I could set it to respond the same way to char input for other numbers allowing the user to only use 1 2 and 3. What method is best? ")

If you have multiple values to check, you can add them to a List and check that this list contains your value (With the method Contains ). You can loop with while until the input is valid.

After that, since your expected values are all numeric, you can then safely convert the input to an int with Convert.ToInt32 .

public static void Main(string[] args)
{
    IEnumerable<string> allowedInputs = new[] {"1", "2", "3"};

    string userInput = "";
    while (!allowedInputs.Contains(userInput))
    {
        Console.WriteLine("Enter 1, 2 or 3");
        userInput = Console.ReadLine();
    }
    int atkChoice = Convert.ToInt32(userInput);

    //Do your if conditions
}

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