Reputation: 3
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
Upvotes: 0
Views: 1973
Reputation: 87
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;
}
Upvotes: 1
Reputation: 1166
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");
Upvotes: 0
Reputation: 189
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");
Upvotes: 1
Reputation: 1985
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");
}
Upvotes: 0