Unable to correct an exception in a C# calculator

The code below produce a simple console calculator that ask the user to select an arithmetic operation, type in two numbers for the operation, and display the output. The process is repeated over and over till user type n or N.

Unfortunately the calculator works only once, after which an exception (FormatException according to the debugger) is thrown by the last line in the code "op = Char.Parse(Console.ReadLine());"

From the exception type (i.e FormatException) its presumably a format mismatch in the input. But I ensured that input is converted from string to char by using the parse method, more oddly the line throws the exception before I even get to type the input (namely +,-,*...etc)

See attached picture of the exact exception message I get below
using System;
using System.Collections.Generic;
using System.Text;
 
namespace Calculator
{
    class Program
    {
        static void Main(string[] args)
        {
 
            Console.WriteLine("Select an operation (+,-,*,/,%). Press n to exit");
            char operat = Char.Parse(Console.ReadLine());
            char op = 'y';
            
 
 
            while (op != 'N' && op != 'n')
            {     
 
                Console.WriteLine("Please enter two numbers");
                double x = double.Parse(Console.ReadLine());
                double y = double.Parse(Console.ReadLine());
 
                //double x = Convert.ToDouble(Console.ReadLine());
                //double y = Convert.ToDouble(Console.ReadLine());
               
 
 
                switch (operat)
                {
                    case '+':
                        Console.WriteLine("You selected addition(+)");
                        Console.WriteLine(x+y);
                        Console.WriteLine("Press enter to continue...");
                        Console.Read();
                        break;
                    case '-':
                        Console.WriteLine("You selected subtration(-)");
                        Console.WriteLine(x - y);
                        Console.WriteLine("Press enter to continue...");
                        Console.Read();
                        break;
                    case '*':
                        Console.WriteLine("You selected multiplication(*)");
                        Console.WriteLine(x * y);
                        break;
                    case '/':
                        Console.WriteLine("You selected division(/)");
                        Console.WriteLine(x / y);
                        Console.WriteLine("Press enter to continue...");
                        Console.Read();
                        break;
                    case '%':
                        Console.WriteLine("You selected modulus(%)");
                        Console.WriteLine(x % y);
                        Console.WriteLine("Press enter to continue...");
                        Console.Read();
                        break;                  
                }
                Console.Clear();
                Console.WriteLine("Select an operation (+,-,*,/,%). Press n to exit");
                op = Char.Parse(Console.ReadLine());
 
            }
 
        }
    }
}

Open in new window

Exception-Message.jpg
a_anis3000Asked:
Who is Participating?
 
Anurag ThakurTechnical ManagerCommented:
try this piece of code out it will work
char operat = 'y';
while (operat != 'N' && operat != 'n')
{
	Console.WriteLine ("Select an operation (+,-,*,/,%). Press n to exit");
	operat = Char.Parse (Console.ReadLine ());
	Console.WriteLine ("Please enter two numbers");
	double x = double.Parse (Console.ReadLine ());
	double y = double.Parse (Console.ReadLine ());
 
	switch (operat)
	{
		case '+':
			Console.WriteLine ("You selected addition(+)");
			Console.WriteLine (x + y);
			Console.WriteLine ("Press enter to continue...");
			Console.ReadLine ();
			break;
		case '-':
			Console.WriteLine ("You selected subtration(-)");
			Console.WriteLine (x - y);
			Console.WriteLine ("Press enter to continue...");
			Console.ReadLine ();
			break;
		case '*':
			Console.WriteLine ("You selected multiplication(*)");
			Console.WriteLine (x * y);
			Console.WriteLine ("Press enter to continue...");
			Console.ReadLine ();
			break;
		case '/':
			Console.WriteLine ("You selected division(/)");
			Console.WriteLine (x / y);
			Console.WriteLine ("Press enter to continue...");
			Console.ReadLine ();
			break;
		case '%':
			Console.WriteLine ("You selected modulus(%)");
			Console.WriteLine (x % y);
			Console.WriteLine ("Press enter to continue...");
			Console.ReadLine ();
			break;
	}
	Console.Clear ();
	//Console.WriteLine ("Select an operation (+,-,*,/,%). Press n to exit");
	//string input = Console.ReadLine ();
	//operat = Char.Parse (input);
}

Open in new window

0
 
AllamzCommented:
as show in the attachment that the string length is greater than 1 and to parse to charcter string should length should only be 1
0
 
AllamzCommented:
a_anis3000,

to avoid this exception you should add some validations to your application. which means
1- Don't allow the user to enter more than one Character in the operation choice.
  ==>this cause the first error because you try to parse to Char which means only 1 letter and maybe the user enters more than one.

please don't hesitate to contact me if you require further assistance.

Best Regards,

Mohamed Allam
Senior Solution Developer
0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

 
a_anis3000Author Commented:
Allamz I know that any attempts to input more than one character will cause an exception, the problem though the exception occurs before I even get to type in the input
0
 
Anurag ThakurTechnical ManagerCommented:
hi, i have already given you the solution
and if you compare your code with mine you will be able ot find the differences and the reason for your code not working
0
 
a_anis3000Author Commented:
Hi ragi0017. I tried your code and its working.Much of it is the same as mine except Console.ReadLine () is used instead of Console.Read(); in the switch statement

I tried replacing Console.Read() with Console.ReadLine() in my code and it worked as well, no exception occurred... Why would both make a difference though? true that they are different in the fact that the ReadLine method reads a line of characters while the Read method only read one character at a time, but shouldn't matter in my case, because in line 36,42,52, or 58 in my code I am asked to press enter to continue, so since I will be inputting a single character (Enter) the use of ReadLine and Read shouldn't not make a difference. Should it?
0
 
Anurag ThakurTechnical ManagerCommented:
you are asking the user to press enter to continue and you are taking care of that by using read
read will leave the enter as an input for next operation and that what was happening
Console.WriteLine("Press enter to continue...");
Console.Read();
0
 
a_anis3000Author Commented:
Probably because character representation for the Enter is several characters long. Presumably the character representation for the Enter key is \r\n (carriage return and new line)  So probably the Read method at line 36,42,52, or 58 in my code reads the first character "\", and the rest "r\n" is read in by the ReadLine method in line 63, and converted into char type, since its obviously more than one character long, the conversion fails and hence an FormatException is thrown. Am I right?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.