My program works correctly. The only thing I am trying to figure out is how to send an error for invalid user input. If a user types in strings or numbers without using spaces, "a * b", "12*5", how can I send an error in a split.
using System;
namespace Calculator1
{
class Program
{
static void Main(string[] args)
{
double answer;
bool Continue = true;
Console.WriteLine("\tCalculator");
Console.WriteLine("--------------------------\n");
Console.WriteLine(" Math Operations: ");
Console.WriteLine(" --------------------");
Console.WriteLine(" Multiplication: *");
Console.WriteLine(" Addition: +");
Console.WriteLine(" Subtraction: -");
Console.WriteLine(" Division: /");
while (Continue)
{
Console.WriteLine("\nEnter your equation below:");
Console.WriteLine(" For example: 5 + 5 ");
string[] values = Console.ReadLine().Split(' ');
double firstNum = double.Parse(values[0]);
string operation = (values[1]);
double secondNum = double.Parse(values[2]);
if (operation == "*")
{
answer = firstNum * secondNum;
Console.WriteLine("\n" + firstNum + " * " + secondNum + " = " + answer);
}
else if (operation == "/")
{
answer = firstNum / secondNum;
Console.WriteLine("\n" + firstNum + " / " + secondNum + " = " + answer);
}
else if (operation == "+")
{
answer = firstNum + secondNum;
Console.WriteLine("\n" + firstNum + " + " + secondNum + " = " + answer);
}
else if (operation == "-")
{
answer = firstNum - secondNum;
Console.WriteLine("\n" + firstNum + " - " + secondNum + " = " + answer);
}
else
{
Console.WriteLine("Sorry that is not correct format! Please restart!");
}
Console.WriteLine("\n\nDo you want to continue?");
Console.WriteLine("Type in Yes to continue or press any other key and then press enter to quit:");
string response = Console.ReadLine();
Continue = (response == "Yes");
}
}
}
}
Calculator
Math Operations:
Multiplication: * Addition: + Subtraction: - Division: /
Enter your equation below: For example: 5 + 5 5*5 //I want to send an error here
Unhandled Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseDouble(ReadOnlySpan`1 value, NumberStyles options, NumberFormatInfo numfmt) at System.Double.Parse(String s) at Calculator1.Program.Main(String[] args) Press any key to continue . . .
Calculator
Math Operations:
Multiplication: * Addition: + Subtraction: - Division: /
Enter your equation below: For example: 5 + 5 a * b //I also want to send an error here
Unhandled Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseDouble(ReadOnlySpan`1 value, NumberStyles options, NumberFormatInfo numfmt) at System.Double.Parse(String s) at Calculator1.Program.Main(String[] args) Press any key to continue . . .