简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM