Reputation: 25
I have to write a code that will ask for 3 integers values and find the greatest one. However, if the user enters a non numeric value this must have the value of zero. So far i wrote this
int a, b, c;
Console.WriteLine("Enter value 1:");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter value 2:");
b = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter value 3:");
c = Convert.ToInt32(Console.ReadLine());
if (a > b && a > c)
{
Console.WriteLine("The greatest value is: {0}", a);
}
if (b > a && b > c)
{
Console.WriteLine("The greatest value is: {0}", b);
}
if (c > a && c > b)
{
Console.WriteLine("The greatest value is: {0}", c);
}
This code works only with numbers. My problem is that i can't make a non numeric input have the value of zero. I tried using string instead of int, so there is no error but i can not make use ">" with strings in the if statements and i also tried using as default, because when is default so it is zero.
Thank you
Upvotes: 0
Views: 1045
Reputation: 90
I think you can create a function that does the try catch, in this way you print a message saying that the input was not a number.
static int Check(string input)
{
int result;
try
{
result = Convert.ToInt32(input);
}
catch (FormatException e)
{
Console.WriteLine("Input not integer, the value assigned is 0");
result = 0;
}
return result;
}
For implementing you just call:
a = Check(Console.ReadLine());
Upvotes: 0
Reputation: 19496
You can just replace:
x = Convert.ToInt32(Console.ReadLine());
With...
int.TryParse(Console.ReadLine(), out int x);
If the input can't be parsed, x
will end up being 0.
Upvotes: 4