简体   繁体   English

同时添加两个数字,如果用户输入字符串如何限制他

[英]while adding two number if user enter string how to restrict him

Here i'm writing a simple c#program Addding two number but if user Enter string sting value how to say him Enter only integer value 在这里,我正在编写一个简单的C#程序,将两个数字相加,但是如果用户输入字符串值,该怎么说呢?

 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);

 }

you could put something like 你可以放一些像

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: ");
}

Try below if you want to continue the program after invalid inputs 如果您想在输入无效后继续执行程序,请尝试以下操作

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);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用正则表达式限制用户仅输入单个字符,即“ Y”和“ N” - how to restrict a user to enter only single character i.e “Y” and “N” using a regular expression 如何限制用户在C#中输入txtPrivateID中的128位和txtPublicID中的128位 - how to restrict user to enter 128 bits in txtPrivateID and 128 bits in txtPublicID in c# 在执行任务时如何限制用户在浏览器中打开多个选项卡? - How to restrict user in opening multiple Tabs in a browser while performing tasks? 显示用户备忘录上还剩下多少个字符 - Show the user how many remaining chars left to him on a memoEdit 如何限制用户输入? - How to restrict user input? 有没有一种方法可以通过为用户提供输入要退出的数字的选项来退出while while循环? - Is there a way to exit this do while loop by giving the user the option to enter a number to exit? 限制每个用户的并发wcf会话数 - Restrict number of concurrent wcf sessions per user 将48添加到字符串编号 - adding 48 to string number 尝试输入连接字符串时捕获到ArgumentException - ArgumentException caught while trying to enter connection string 加载时如何在 C# 代码中限制字符串开头和结尾的空格。csv 文件 - How to Restrict a blank space at start and end of the string in C# code while loading .csv file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM