这里我写了一个简单的c#程序添加两个数字但是如果用户输入字符串sting值怎么说他只输入整数值
int x;
int y;
int result;
string Res2;
Console.Write("\n Enter the first number to be added: ");
x = Convert.ToInt32(Console.ReadLine());
Console.Write("\n Enter the second number to be added: ");
y = Convert.ToInt32(Console.ReadLine());
if (x != null && y != null)
{
result = x + y;
Console.Write("\n The sum of two numbers is: " + result);
}
答案 0 :(得分:2)
你可以放点像
int x;
Console.Write("\n Enter the first number to be added: ");
while(!int.TryParse(Console.ReadLine(),out x))
{
Console.Write("\nPlease, enter a valid number: ");
}
答案 1 :(得分:0)
如果您想在无效输入后继续播放程序
,请尝试以下操作string x,y;
int a,b;
int result;
bool flag = false;
do{
if(flag)
Console.Write("\n Please enter integer values");
Console.Write("\n Enter the first number to be added: ");
x = Console.ReadLine();
Console.Write("\n Enter the second number to be added: ");
y = Console.ReadLine();
flag = true;
}
while(!int.TryParse(x, out a) || !int.TryParse(y, out b));
if (x != null && y != null)
{
result = a + b;
Console.Write("\n The sum of two numbers is: " + result);
}