0

I wonder how to print an error message if user's input is not a number.

Console.WriteLine("Water amount in ml:");
        int waterAmount = Convert.ToInt32(Console.ReadLine());

Most answers from other posts don't work, because waterAmount is a Int32, not a string. Also, sorry if my English is weak, it's not my native language

1
  • 3
    Use TryParse() and if it is false write the message. Commented Jul 18, 2020 at 12:02

4 Answers 4

1

You can try using C#'s TryParse() functions. These attempt to convert values, but if they fail they return false rather than erroring.

I would suggest trying this code:

Console.WriteLine("Water amount in ml:");
string input = Console.ReadLine();

if (Int32.TryParse(input, out var value))
    // Do something here. The converted int is stored in "value".
else
    Console.WriteLine("Please enter a number");
Sign up to request clarification or add additional context in comments.

Comments

1

I see you did not accept the other answers. Maybe you want to make the user try again after he did not input a number. You can do that with a while loop, or easier, using the goto keyword. You simply put a tag before everything is happening (in my case, waterAmountInput), and if the input was not a number, you write your error message and go to the beginning again. Here is the code:

        int waterAmount;

        waterAmountInput:
        Console.Write("Water amount in ml: ");
        try
        {
            waterAmount = Convert.ToInt32(Console.ReadLine());
        }
        catch
        {
            Console.WriteLine("The water amount needs to be a number!");
            goto waterAmountInput;
        }

1 Comment

Thanks, that's my first project ever and i really needed this advice.
0

You should use TryParse function:

Console.WriteLine("Water amount in ml:");
int waterAmount = 0;
if (int.TryParse(Console.ReadLine(), waterAmount)) {

} else {
    Console.WriteLine("Error Message");
}

Comments

0

You will need to use TryParse before presuming it to be a number. After Console.WriteLine you can capture and parse the input and if TryParse returns false, you can display an error message.

Note: if the conversion succeeds the numeric value is available in the waterAmt local variable.

Console.WriteLine("Water amount in ml:");
var input = Console.ReadLine();
if(!int.TryParse(input, out int waterAmt))
      Console.WriteLine("Input is not a number");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.