Loop, Validation, Environment NewLine and Switch Case
I am trying to write a program which combine like Loop and Validation, DiplayMenu for UserOption Using Environment Newline, and Switch Case in a single Program. How do I go about achieving it?
Here is the Script I am currently working on:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CalculatorApplication2
{
class CalculatorApplication2
{
static void Main(string[] args)
{
// Create local variables
int userOption = 0;
int num1 = 0;
int num2 = 0;
string operation;
double result = 0;
// End create local variables
// Display the menu
while (userOption != 5)
{
userOption = DisplayMenu();
if (userOption == 5)
return;
// Get the numbers
Console.Write("Please enter the first number and press the enter key: ");
Console.WriteLine();
num1 = gettheNumber();
num1 = int.Parse(Console.ReadLine());
Console.Write("Please choose an operation (+, -, /, *): ");
operation = Console.ReadLine();
Console.Write("Please enter the second number and press the enter key: ");
num2 = getthenumber();
num2 = int.Parse(Console.ReadLine());
//Calculation Action
switch (operation)
{
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num1 / num2;
break;
default:
Console.WriteLine("Error!");
result = 0.0;
break;
{
// Take action
}
// Print the result
Console.WriteLine("The result of your action is: " + result);
}
// End display menu
}
///Display the actual menu
///<returns>Returns an int that represents theuser's action</returns>
private static int DisplayMenu()
{
// DisplayMenu using Enviroment NewLine
Console.WriteLine("Enter the number corresponding to the action that you would like to perform.");
Console.WriteLine( "\n 1) Addition"
+"\n 2) Substraction"
+"\n 3) Multiplication"
+"\n 4) Division"
+"\n 5) End Program");
// Get the option
Console.WriteLine("{0} {1} {2} = {3}", num1, operation, num2, result);
Console.WriteLine(num1.ToString() + " " + operation + " " + num2.ToString() + " = " + result.ToString());
Console.ReadLine();
//Validation script
do
{
Console.Write("Enter operation ('+','-','\','*'): ");
operation = Console.ReadLine();
Console.WriteLine();
int input;
bool isValid = int.TryParse(operation.ToString(), out input);
if (!isValid || operation != "-" || operation != "+" ||
operation != "*" || operation != "/")
{
Console.WriteLine("You can enter only valid operations!");
}
} while (operation != "-" && operation != "+" && operation != "*" && operation != "/");
}
}
}