user1892117
user1892117

Reputation: 25

Validating input value from console without exiting loop C#

Lets say for a console application, I want the user to enter how many dices he would like to throw. Onlu values 1-5 will be accepted. I tried doing this:

Console.WriteLine("How many dices would you like to throw?");
int amount = Convert.ToInt32(Console.ReadLine());

while(true)
{
 if(amount < 1 || amount > 5)
 {
     Console.WriteLine("Please enter a value between 1-5");
     break;
 } 
}

The problem here is that if the user enters an invalid number, the program stops. I want it to simply continue asking until correct value is inputed. Any ideas?

cheers.

Upvotes: 0

Views: 387

Answers (2)

Barns
Barns

Reputation: 4848

You might want to check if the entered value is actually an integer.

        int amount;
        Console.WriteLine("How many dices would you like to throw?");
        do
        {
            if (int.TryParse(Console.ReadLine(), out var i))
            {
                if (i >= 1 && i <= 5)
                {
                    amount = i;
                    break;
                }
                Console.WriteLine("The integer value is not between 1 and 5");
            }
            {
                Console.WriteLine("The value you entered is not an integer");
            }
        } while (true);


EDIT
I generally like to give the user the option to exit completely.

        int amount;
        Console.WriteLine("How many dices would you like to throw? Or enter 'X' to exit.");
        do
        {
            var input = Console.ReadLine();
            if(input.Equals("X", StringComparison.InvariantCultureIgnoreCase))
            {
                return;
            }

            if (int.TryParse(input, out var i))
            {
                if (i >= 1 && i <= 5)
                {
                    amount = i;
                    break;
                }
                Console.WriteLine("The integer value is not between 1 and 5");
            }
            {
                Console.WriteLine("The value you entered is not an integer");
            }
        } while (true);

Upvotes: 0

Nazim
Nazim

Reputation: 639

I haven't tested it but slightly refactored your code as below, it should do what you want:

Console.WriteLine("How many dices would you like to throw?");
int amount = Convert.ToInt32(Console.ReadLine());

while(amount < 1 || amount > 5)
{
    Console.WriteLine("Please enter a value between 1-5");
    amount = Convert.ToInt32(Console.ReadLine());
}

EDIT: if you want to safely check whether it is an integer value, you can use the below version of code:

    Console.WriteLine("How many dices would you like to throw?");
    var input = Console.ReadLine();

    while(!int.TryParse(input, out int amount) || amount < 1 || amount > 5)
    {
        Console.WriteLine("Please enter a value between 1-5");
        input = Console.ReadLine();
    }

Upvotes: 1

Related Questions