Adding an error message when a user inputs a decimal number [duplicate]

I’m trying to create a simple calculator using c# that, when I input decimal numbers, will prompt an error message instead of just directly going into unhandled exception.

do{
            Console.Write("X = ");
            string str = Console.ReadLine();
            if(str == "exit"){
            Console.WriteLine("Program has been stopped");
            break;
        }
        else{
         int x = Convert.ToInt32(str);
         Console.Write("Y = ");
         int y = Convert.ToInt32(Console.ReadLine());
        
         Console.WriteLine("What operation would you like to do?: +, - *, /");
         string operation = Console.ReadLine();
            
            switch(operation){
                case "+":
                Console.WriteLine("The answer is: " + (x + y));
                break;
                    
                case "-":
                Console.WriteLine("The answer is: " + (x - y));
                break;
                    
                case "*":
                Console.WriteLine("The answer is: " + (x * y));
                break;
                    
                case "/":
                Console.WriteLine("The answer is: " + (x / y));
                break;
            
            }
        }}
            while(true);
            

  • You can use try/catch or int.TryParse().

    – 

If you are writing a calculator then you should be using decima or double instead of int data type. You will end up with a decima type result at some point specially when user decides to use the division operator. For example ‘3/2’.

Also should never parse any input from the user without proper validations. For example length check.

Change your parsing code to this:

int x;
if(int.TryParse(str, out x))
{
   Console.Write("Y = ");
   string varY = Console.ReadLine();
   int y;
   if(int.TryParse(varY, out y))
   {
      Console.WriteLine("What operation would you like to do?: +, - *, /");
      ...<Your other codes goes here>...
   }
}

The above code ensures that you have valid x and y. Implement Else statement like please input a valid number for better user experience. Also check the length of the input.

Change the above int to decimal for correct result in case user inputs / for the operator.
Also instead of int.TryParse you can have decimal.TryParse or double.TryParse

Leave a Comment