[英]C# How set a non-numeric value to 0
I have to write a code that will ask for 3 integers values and find the greatest one.我必须编写一个代码来要求 3 个整数值并找到最大的一个。 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.我尝试使用字符串而不是 int,所以没有错误,但我不能在 if 语句中使用 ">" 字符串,我也尝试使用默认值,因为默认值是什么,所以它为零。
Thank you谢谢
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.如果无法解析输入,则x
最终将为 0。
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.我认为您可以创建一个执行 try catch 的 function,这样您就可以打印一条消息,说明输入不是数字。
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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.