using loops and methods together - c#

Recently i made a simple calculator to test myself but it was clunky and cluttered because it used a large number of if statements so i used switches to clean it up. recently i learned how to use methods and tried to move each part of the code into a separate and relevant methods. But, some of my code uses loops to return to the start of the code to act as a reset function and now it doesn't work because it doesn't recognize that it is a part of a loop. i tried calling all the methods in a loop inside the main method but it still didn't work. how can i fix this?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace Calculator
{
class Class1
{
static int num1 = 0;
static int num2 = 0;
static int answer = 0;
static string sumType = " ";
static string consoleContinue = " ";
static void GetUserInput()
{
Console.WriteLine("please enter your first value");
num1 = int.Parse(Console.ReadLine());
Console.WriteLine("please enter your second value");
num2 = int.Parse(Console.ReadLine());
}
static void GetSumType()
{
Console.WriteLine("would you like to add, subtract, multiply or divide?");
Console.WriteLine("alternitavely type quit to exit the program");
sumType = Console.ReadLine();
switch (sumType.ToLower())
{
case "add":
answer = (num1 + num2);
Console.WriteLine("your answer is {0:0.00}", answer);
break;
case "subtract":
answer = (num1 - num2);
Console.WriteLine("your answer is {0:0.00}", answer);
break;
case "multiply":
answer = (num1 * num2);
Console.WriteLine("your answer is {0:0.00}", answer);
break;
case "divide":
answer = (num1 / num2);
Console.WriteLine("your answer is {0:0.00}", answer);
break;
case "quit":
Environment.Exit(-1);
break;
}
}
static void ConsoleContnue()
{
Console.WriteLine("do you wish to continue? type yes to continue and no to exit the program");
consoleContinue = Console.ReadLine();
switch (consoleContinue.ToLower())
{
case "yes":
continue;
break;
case "no":
Environment.Exit(-1);
break;
}
}
static void Main(string[] args)
{
while (true)
{
GetUserInput();
GetSumType();
ConsoleContnue();
}
Console.ReadLine();
}
}
}

In your "ConsoleContnue()" function -> in the switch statement for "yes" you can remove the "continue" so it looks like this:
switch (consoleContinue.ToLower())
{
case "yes":
break;
case "no":
Environment.Exit(-1);
break;
}
Then your code seems to run perfectly.
However, I would change it to a simple one liner since you only care about the "no" clause:
if (consoleContinue.ToLower() == "no") Environment.Exit(-1);

Related

A problem with getting/printing answers in a C# calculator

I'm trying to make simple projects for learning C# and have tried to make a simple console calculator. I have only found this current error when getting to the getting/printing the answer bit when test-running my program, so I have no idea if there are any other errors/things that will or may not work or run properly/as intended. So if there are any of those, please let me know and if you want to you can fix them yourself. It only recognized the error when it reached that specific line of code, and otherwise will run the program until it reaches the error.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Calculator
{
class Program
{
static void Main(string[] args)
{
string num1;
string num2;
string condition;
string answer;
Console.WriteLine("Calculator");
Console.WriteLine("For division, use /. For multiplication, use *.\n");
while (true)
{
Console.WriteLine("Enter a number: "); // gets first number to add in problem
num1 = Console.ReadLine();
Console.WriteLine("Enter a condition: "); // gets condition to add in problem
condition = Console.ReadLine();
Console.WriteLine("Enter your second number: "); // gets second number to add in problem
num2 = Console.ReadLine();
Console.WriteLine("Calculating..");
// converting strings to int and working out answer
Convert.ToInt32(num1);
Convert.ToInt32(num2);
// error is from here on (not sure if the Convert.ToInt32() code above causes errors)
answer = num1 + condition + num2;
Convert.ToInt32(answer);
Console.WriteLine(answer);
// sets values to null after getting & printing answer (probably unnessessary)
answer = null;
num1 = null;
num2 = null;
condition = null;
}
}
}
}
When facing problems like this one - the routine is too complex to be tested:
if there are any other errors/things that will or may not work"
split routine into smaller ones: start extracting methods.
// Get integer value from user
public static int ReadInteger(string title) {
while (true) {
if (!string.IsNullOrEmpty(title))
Console.WriteLine(title);
if (int.TryParse(Console.ReadLine(), out int result))
return result;
Console.WriteLine("Sorry, not a valid integer value, please, try again.");
}
}
// Get character operator ('+', '-' etc.) from user
public static char ReadOperator(string title, string operators) {
while (true) {
if (!string.IsNullOrEmpty(title))
Console.WriteLine(title);
string input = Console.ReadLine().Trim();
if (input.Length == 1 && operators.Contains(input[0]))
return input[0];
Console.WriteLine("Sorry, not a valid operator, please, try again.");
}
}
Now we are ready to implement Main method:
static void Main(string[] args) {
while (true) {
int num1 = ReadInteger("Enter a number: ");
char op = ReadOperator("Enter a condition: ", "+-*/");
int num2 = ReadInteger("Enter your second number: ");
//TODO: I've skipped error handling (zero division, overflow)
int answer =
op == '+' ? num1 + num2 :
op == '-' ? num1 - num2 :
op == '*' ? num1 * num2 :
op == '/' ? num1 / num2 : 0;
Console.WriteLine($"{num1} {op} {num2} = {answer}");
//TODO: it's a right place here to ask user if (s)he wants to continue
Console.WriteLine();
}
}
You receive input (condition) as a string
cant do this : answer = num1 + condition + num2 because those variables are
string
you have to check that with switch , for example :
int num1 = 0, num2 = 0, answer = 0;
string condition;
Console.WriteLine("Calculator");
Console.WriteLine("For division, use /. For multiplication, use *.\n");
while (true)
{
Console.WriteLine("Enter a number: "); // gets first number to add in problem
num1 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter a condition: "); // gets condition to add in problem
condition = Console.ReadLine();
Console.WriteLine("Enter your second number: "); // gets second number to add in problem
num2 = int.Parse(Console.ReadLine());
Console.WriteLine("Calculating..");
// converting strings to int and working out answer
Convert.ToInt32(num1);
Convert.ToInt32(num2);
// error is from here on (not sure if the Convert.ToInt32() code above causes errors)
switch (condition)
{
case "/":
answer = num1 / num2;
break;
case "*":
answer = num1 * num2;
break;
case "+":
answer = num1 + num2;
break;
case "-":
answer = num1 - num2;
break;
default:
Console.WriteLine("error : unknown operator");
break;
}
Console.WriteLine(answer);
// sets values to null after getting & printing answer (probably unnessessary)
}
You can't do this line because all the variables are strings and not the real values (e.g: num1 & num2 should ints/doubles... and condition should be a real operator).
answer = num1 + condition + num2;
Also, you can't do it because let's assume the user inputs the multiplication sign, and then the string of "*" is not equal to the sign of *.
Instead, you can do some switch-case statements to check the value of the condition variable. Also, you need to make sure num1 & num2 are numbers (you can parse/try-parse them to a number (int/double...)). You will also have to parse them to another variables as they are strings.
switch (condition)
{
case '*':
answer = numX * numY;
break;
case "/":
// Validate that numY is not 0 to avoid [DivideByZeroException][1]
answer = numX / numY;
break;
...
}
Note, it is just one way to do it and I just gave you a small example that might help you to continue.
I would also offer you to make a default case (in case that the input of the user is not something you expect, in this case, you may ask him again to write an input because the current input is invalid).

First console application returning with unexpected output

When I run this console app, everything works fine but except for my UserAnswer() result. It keeps returning a value of '0' for both num1 & num2. This doesn't make sense to me because I don't receive any errors for declaring a new value for num1 & num2 in Input1() & Input2() methods. It compiles and runs fine but why is it not picking up the new values of these variables?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CalculatorApp
{
public class Program
{
float Number;
float num2;
float num1;
public static void Main(string[] args)
{
// Display title as the C# console calculator app.
Console.WriteLine("Console Calculator in C#\r");
Console.WriteLine("------------------------\n");
//Console.ReadKey();
// execute program functions
new Program().Input1();
new Program().Input2();
new Program().UserOption();
new Program().UserAnswer();
new Program().PromptUserExit();
}
// Ask the user to type the first number.
//Console.WriteLine("Type a number, and then press Enter");
public float Input1() {
Console.WriteLine("Type a number, and then press Enter");
bool Valid = false;
while (Valid == false)
{
string Input = Console.ReadLine();
if (!float.TryParse(Input, out Number))
{
Console.WriteLine("Not an integer, please try again.");
}
else
{
Valid = true;
num1 = (float)Convert.ToDecimal(Input);
}
} return num1;
}
public float Input2() {
// Ask the user to type the second number.
Console.WriteLine("Type another number, and then press Enter");
bool Valid2 = false;
while (Valid2 == false)
{
string Input2 = Console.ReadLine();
if (!float.TryParse(Input2, out Number))
{
Console.WriteLine("Not an integer, please try again.");
}
else
{
Valid2 = true;
num2 = (float)Convert.ToDecimal(Input2);
}
} return num2;
}
public void UserOption() {
// Ask the user to choose an option.
Console.WriteLine("Choose an option from the following list:");
Console.WriteLine("\ta - Add");
Console.WriteLine("\ts - Subtract");
Console.WriteLine("\tm - Multiply");
Console.WriteLine("\td - Divide");
Console.Write("Your option? ");
}
public void UserAnswer() {
bool isOperatorValid;
do
{
isOperatorValid = true;
switch (Console.ReadLine())
{
case "a":
Console.WriteLine($"Your result: {num1} + {num2} = " + (num1 + num2));
break;
case "s":
Console.WriteLine($"Your result: {num1} - {num2} = " + (num1 - num2));
break;
case "m":
Console.WriteLine($"Your result: {num1} * {num2} = " + (num1 * num2));
break;
case "d":
Console.WriteLine($"Your result: {num1} / {num2} = " + (num1 / num2));
break;
default:
Console.WriteLine("Invalid input please try again");
isOperatorValid = false;
break;
}
} while (!isOperatorValid);
}
public void PromptUserExit() {
// Wait for the user to respond before closing.
Console.Write("Press any key to close the Calculator console app...");
Console.ReadKey();
}
}
}
This is your problem:
new Program()
You are creating a new instance of the Program class every time you call a method. Each time, the variables are initialized with the default value of 0.
You need to initialize the class once, then use the same class:
var program = new Program();
program.Input1();
program.Input2();
program.UserOption();
program.UserAnswer();
program.PromptUserExit();
Or you could just make all of your methods and variables static so that you can call them directly without initializing a new object. In bigger programs, you would want to be careful with declaring things static (there is a time and place, but it's not "always"). But in a small program like this, it's fine.

console.clear placement within a looping program

Hi i have been looking for where to put my console.clear because i have made a looping program but i would like to clear after use. Could any one tell me where to put a console.clear or give me a push in the right direction at least. Sorry i am very new to C# and have an assignment due in pretty soon and i am panicing that i havent got my Console.Clear command sorted yet. Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment_test
{
class Program
{
static void Main(string[] args)
{
Console.Clear();
//when creating the variable i would of used byte however it wasn't picking it up so i had to use int which i know isnt effective use of memory
int sUserChoice = 0;
do
{
//this makes the text yellow
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Welcome to Hit ‘n’ Miss Ltd");
Console.WriteLine("Please select an option:");
Console.WriteLine("\n\n 1 for Welcoming to the system");
Console.WriteLine("\n 2 for the mean of grades of the class");
Console.WriteLine("\n 3 for what month it is");
Console.WriteLine("\n 4 for adds numbers between -10 and +10 and adds them together");
Console.WriteLine("0 is quit");
Console.Write("\n Please enter a number: ");
int.TryParse(Console.ReadLine(), out sUserChoice);
 
 
 
 
 
 
switch (sUserChoice)
{
case 1:
//here i say that to start talking about the parameter that i shall be using
WelcomeToTheSystem();
break;
case 2:
// here i call apon the parameter used
Grades();
break;
case 3:
// here i call apon the parameter used
Months();
break;
case 4:
// here i call apon the parameter used
AddingNegitiveAndPossitiveNumbers();
break;
// here i call apon the parameter used
case 0:
Quit();
break;
}
} while (sUserChoice != 0);
 
 
Console.ReadKey();
}
//start of prodecdures and funtions
private static int DataVaildation()
{
//variables
bool bUserInput;
int iNumber;
//below is a loop that runs at least once. the loop continues
//iterating while the condition evaluates to true, otherwise it ends
//and control goes to the statement immediately after it.
do
{
Console.Write("Please enter a number: ");
//converts string into int
bUserInput = Int32.TryParse(Console.ReadLine(), out iNumber);
//this will be true if the user input could not be converted for instance a word is used
if (!bUserInput)
{
Console.WriteLine("Input could not be converted into an integer number");
continue;
}
//the validation so if the inputted number from the user it will reject int and do the console.writeline.
if (iNumber < -11 || iNumber < 11)
{
//the error message
Console.WriteLine("Your are out of range please stay between -10 and +10");
bUserInput = false;
}
//the number is in range
else
{
Console.WriteLine("Vaild number!");
//if bUserInput is true then the loop can end.
bUserInput = true;
}
} while (!bUserInput);//while this evaluates to true, the loop continues.
return iNumber;
}
//option 4
private static void AddingNegitiveAndPossitiveNumbers()
{
Console.WriteLine("Please give me 2 number between -10 and +10 and ill add them together\n");
//calls apon the private static int above
int iNumber1 = DataVaildation();
int iNumber2 = DataVaildation();
//the adding will be done here
int iResult = iNumber1 + iNumber2;
Console.WriteLine("The sum of {0} + {1} is {2}", iNumber1, iNumber2, iResult);
}
//data validation
//option 3
private static void Months()
{
Console.WriteLine("so pick a number between 1 and 12. 1 is january and 12 december");
//here i declare that int is a variable
int iMonths = 0;
//i then will tryparse if someone inputs an invalid number
int.TryParse(Console.ReadLine(), out iMonths);
Console.ReadKey();
//i start a switch statement
switch (iMonths)
{
//if the user selects a number it will display the month this is done by using case to get the users input
case 1:
Console.WriteLine("It's January");
break;
case 2:
Console.WriteLine("It's Febuary");
break;
case 3:
Console.WriteLine("It's March");
break;
case 4:
Console.WriteLine("It's April");
break;
case 5:
Console.WriteLine("It's May");
break;
case 6:
Console.WriteLine("It's June");
break;
case 7:
Console.WriteLine("It's July");
break;
case 8:
Console.WriteLine("It's August");
break;
case 9:
Console.WriteLine("It's September");
break;
case 10:
Console.WriteLine("It's October");
break;
case 11:
Console.WriteLine("It's Novemeber");
break;
case 12:
Console.WriteLine("It's December");
break;
}
}
//0
private static void Quit()
{
//this bit exits the code if you press 0
System.Environment.Exit(0);
}
//1
private static void WelcomeToTheSystem()
{
Console.WriteLine("Please enter a name: ");
//used string here because its text
string sName =
Console.ReadLine();
Console.WriteLine("Welcome to the system: " + sName);
Console.ReadKey();
}
//2
private static void Grades()
{
int[] array1 = new int[15];
Console.WriteLine("please give me 15 numbers and i will give you the average of them");
for (int i = 0; i < array1.Length; i++)
{
while (int.TryParse(Console.ReadLine(), out array1[i]) == false)
{
Console.WriteLine("Please give me a number not text");
}
}
////here the averaging takes place it basscially averages the array that it has and adds + to every user input
Console.WriteLine("The average is {0} / 15 = {1}", string.Join("+", array1), array1.Average());
}
}
}
I would suggest place it at the beging of your cycle.
something like this:
do
{
...
//this makes the text yellow
Console.Clear();
Console.ForegroundColor = ConsoleColor.Yellow;
...
}
I would suggest writing a small method that asks if you want to continue. If so, Clear screen and then re-display everything
private static void WouldYouLikeToContinue()
{
Console.Write("Would you like to continue? [n to quit]: ");
string input = Console.ReadLine();
if (input.ToLower() == "n")
Quit();
Console.Clear(); // <--- This is where I would suggest adding the Clear.
}
you can use this method after the switch block
switch (sUserChoice)
{
case 1:
//here i say that to start talking about the parameter that i shall be using
userName = WelcomeToTheSystem();
break;
case 2:
// here i call apon the parameter used
Grades();
break;
case 3:
// here i call apon the parameter used
Months();
break;
case 4:
// here i call apon the parameter used
AddingNegitiveAndPossitiveNumbers();
break;
// here i call apon the parameter used
case 0:
Quit();
break;
}
WouldYouLikeToContinue(); // <----- HERE
} while (sUserChoice != 0);
NOTE: Your method to validate data... has a syntax error.
if (iNumber < -11 || iNumber > 11) // iNumber should be > 11 (not < 11)

Allowing user to choose to display entire number in calculator or only 2 decimals

I'm making a basic calculator and I'm wondering how I would go on to make the user choose if he/she wants to display the full result or only the result with 2 decimals. For example, if user puts in first number 4.213 and second number 4.6321, method "+" then the console asks "Do you wish to display the entire result or round it to 2 decimals" at which the user can type in "Yes" or "No".
I'm not looking for the program to round up the decimals, just display 2 decimals or the entire number.
I'm guessing if and else statement would be the way to go here.
Code:
using System.Collections.Generic;
namespace ConsoleApp1
{
class Program
{
private static int runda;
static void Main(string[] args)
{
List<double> Numbers = new List<double>();
string Method = "";
while (true)
{
loop:
try
{
Numbers.Add(ConvStr(TakeUserInput("First Number:")));
}
catch
{
Console.Clear();
Console.WriteLine("Error, try again.");
Console.ReadLine();
goto loop;
}
Console.Clear();
looop:
try
{
Numbers.Add(ConvStr(TakeUserInput("Second Number:")));
}
catch
{
Console.Clear();
Console.WriteLine("Error, try again.");
Console.ReadLine();
goto looop;
}
Console.Clear();
do
{
Method = TakeUserInput("Choose method: ");
Console.Clear();
Console.WriteLine("Error (Endast Addition (+) Subtraktion (-) Multiplikation (*) samt division (/)");
}
while (!CheckMethod(Method));
Console.Clear();
**HERE IS WHERE I WOULD LIKE USER TO CHOOSE IF DISPLAY ENTIRE NUMBER OR ONLY 2 DECIMALS**
Console.WriteLine("Result:");
Console.WriteLine(Calc(Numbers, Method));
Console.WriteLine("If you wish to keep using this calculator press Enter.");
Console.ReadLine();
Numbers.Clear();
}
}
private static string TakeUserInput(string DisplayText)
{
Console.Write(DisplayText);
return Console.ReadLine();
}
private static bool CheckMethod(string method)
{
switch(method)
{
case "+":
break;
case "-":
break;
case "*":
break;
case "/":
break;
default:
return false;
}
return true;
}
private static double Calc(List<double> input, string method)
{
double Answer = 0;
switch (method)
{
case "+":
Answer = input[0] + input[1];
break;
case "-":
Answer = input[0] - input[1];
break;
case "*":
Answer = input[0] * input[1];
break;
case "/":
Answer = input[0] / input[1];
break;
}
return Answer;
}
private static double ConvStr(string input)
{
return Convert.ToDouble(input = input.Replace(".", ","));
}
}
}
Might be wrong but couldn’t you
1). Turn the integer(result) into a string
2). Use the .indexOf(“”) function on the string to get the location of the period
3). check the index+3 to be in range of the result in order to not give any errors (3 to skip the period as well)
4). Use the .remove(index) function to remove all other numbers at the new index
5). Use Convert.toInt32(string) to get its value back
Also there is a “Data.” something function which enables you to calculate the result of a string representation of the expression if that is of any help

Print message when invalid data entered in console application using switch C#

Im trying to write a basic calculator with a main menu and sub menu.
The code is working fine when a valid entry is inputted, but I want an error message to be displayed and then return the user to the main menu when invalid data is entered.
This is what I have done so far. Can someone tell me what am I doing wrong?
static void Main(string[] args)
{
// Main method (only to be used for mainmenu() execution)
MainMenu();
}
// Main Menu method
static void MainMenu()
{
// Declaring variables
// Selection variable, used in user's input to get to the desired operation
int sel;
char letter;
// Main menu styling
Console.WriteLine("Calculator");
Console.WriteLine("********************");
Console.WriteLine("1- Calculator");
Console.WriteLine("2- Exit Calculator");
Console.Write("Please enter your option here: ");
// Converting user's input to sel's type (byte)
sel = int.Parse(Console.ReadLine());
// Processing sel
switch (sel)
{
case 1:
// Execute Addition()
SecondMenu();
break;
case 2:
Console.ReadLine();
break;
default:
Console.WriteLine("Sorry that is not correct format! Please restart!"); //Catch
break;
}
}
static void SecondMenu()
{
char sel2; // Selection variable, used in user's input to get to the desired operation
// Display Menu Options
Console.WriteLine("");
Console.WriteLine("********************");
Console.WriteLine("A. Addition");
Console.WriteLine("S. Substraction");
Console.WriteLine("D. Division");
Console.WriteLine("********************");
Console.Write("Please enter your option here: ");
// Converting user's input to sel's type (byte)
sel2 = Convert.ToChar(Console.ReadLine());
// Processing sel
switch (sel2)
{
case 'a':
// Execute Addition()
Addition();
break;
case 's':
// Execute Substraction()
Substraction();
break;
case 'd':
// Execute Division()
Division();
break;
}
}
// Addition Method
static void Addition()
{
// Declaring variables
double num1, num2, res;
Console.Write("Please enter the first number: ");
// Getting user's input and converting it
num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Please enter the second number: ");
// Getting user's input and converting it
num2 = Convert.ToDouble(Console.ReadLine());
// Processing numbers into one variable
res = num1 + num2;
// Printing out the result
Console.WriteLine("RESULT: " +res);
Console.WriteLine("");
Console.ReadKey(true);
MainMenu();
}
// Substraction Method
static void Substraction()
{
// Declaring variables
double num1, num2, res;
Console.Write("Please enter the first number: ");
// Getting user's input and converting it
num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Please enter the second number: ");
// Getting user's input and converting it
num2 = Convert.ToDouble(Console.ReadLine());
// Processing numbers into one variable
res = num1 - num2;
// Printing out the result
Console.WriteLine("RESULT: " + res);
Console.ReadKey(true);
MainMenu();
}
// Division
static void Division()
{
// Declaring variables
double num1, num2, res;
Console.Write("Please enter the first number: ");
// Getting user's input and converting it
num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Please enter the second number: ");
// Getting user's input and converting it
num2 = Convert.ToDouble(Console.ReadLine());
// Processing numbers into one variable
res = num1 / num2;
// Printing out the result
Console.WriteLine("RESULT: " + res);
Console.WriteLine("");
Console.ReadKey(true);
MainMenu();
}
You can call the MainMenu() method in the default part of the switch in it.
switch (sel)
{
case 1:
// Execute Addition()
SecondMenu();
break;
case 2:
Console.ReadLine();
break;
default:
Console.WriteLine("Sorry that is not correct format!");
MainMenu();
//Catch
break;
}
It is also recommended to have a condition to exit the program (like a maximum number of invalid inputs).
Something like this works, but you'll have to adjust accordingly to fit your requirements:
int sel;
char letter;
bool valid = false;
do
{
Console.WriteLine("Calculator");
Console.WriteLine("********************");
Console.WriteLine("1- Calculator");
Console.WriteLine("2- Exit Calculator");
Console.Write("Please enter your option here: ");
sel = int.Parse(Console.ReadLine());
switch (sel)
{
case 1:
SecondMenu();
break;
case 2:
Environment.Exit(0);
break;
default:
Console.WriteLine("Sorry that is not correct format! Please restart!");
break;
}
}
while (valid != true);
You could just do it like this
static void SecondMenu()
{
char sel2; // Selection variable, used in user's input to get to the desired operation
// Display Menu Options
Console.WriteLine("");
Console.WriteLine("********************");
Console.WriteLine("A. Addition");
Console.WriteLine("S. Substraction");
Console.WriteLine("D. Division");
Console.WriteLine("********************");
Console.Write("Please enter your option here: ");
sel2 = Convert.ToChar(Console.ReadLine());
switch (sel2)
{
case 'a':
Calc(1);
break;
case 's':
Calc(2);
break;
case 'd':
Calc(3);
break;
default:
Console.WriteLine("Wrong entry! Try again");
MainMenu();
return;
}
}
static void Calc(int f)
{
double num1, num2, res;
try
{
Console.Write("Please enter the first number: ");
num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Please enter the second number: ");
num2 = Convert.ToDouble(Console.ReadLine());
switch (f)
{
case 1:
res = num1 + num2;
break;
case 2:
res = num1 - num2;
break;
case 3:
res = num1 / num2;
break;
default:
Console.WriteLine("Wrong entry! Try again");
MainMenu();
return;
}
Console.WriteLine("RESULT: " + res);
Console.WriteLine("");
Console.ReadKey(true);
MainMenu();
}
catch
{
Console.WriteLine("Wrong entry! Try again");
MainMenu();
}
}
EDIT: To make sure the first menu wont crash, sorround it with a try catch block
try
{
sel = int.Parse(Console.ReadLine());
switch (sel)
{
case 1:
SecondMenu();
break;
case 2:
Console.ReadLine();
break;
default:
Console.WriteLine("Sorry that is not correct format! Please restart!");
MainMenu();
break;
}
}
catch
{
Console.WriteLine("Sorry that is not correct format! Please restart!");
MainMenu();
}
Your problem was, that it tried to parse a char into an int, what is not possible.
You can either write the switch case in another method and call the main method at the default case after printing the error message,
OR
Use a do-while loop,
Inside do, write the switch cases and put a condition at while to exit the calculator.
For example: 'Enter -1 to exit the calculator' and condition in while x!=-1
Try having a play with this:
static void Main(string[] args)
{
MainMenu();
}
static void MainMenu()
{
int sel = -1;
while (sel != 2)
{
Console.WriteLine("Calculator");
Console.WriteLine("********************");
Console.WriteLine("1- Calculator");
Console.WriteLine("2- Exit Calculator");
Console.Write("Please enter your option here: ");
sel = int.Parse(Console.ReadLine());
if (sel == 1)
{
SecondMenu();
}
else if (sel != 2)
{
Console.WriteLine("Sorry that is not correct format! Please restart!"); //Catch
}
}
}
static void SecondMenu()
{
var options = new Dictionary<char, Func<double, double, double>>()
{
{ 'a', (x, y) => x + y },
{ 's', (x, y) => x - y },
{ 'd', (x, y) => x / y },
};
while (true)
{
Console.WriteLine("");
Console.WriteLine("********************");
Console.WriteLine("A. Addition");
Console.WriteLine("S. Substraction");
Console.WriteLine("D. Division");
Console.WriteLine("********************");
Console.Write("Please enter your option here: ");
char sel = Convert.ToChar(Console.ReadLine());
if (options.ContainsKey(sel))
{
Calculate(options[sel]);
break;
}
}
}
static void Calculate(Func<double, double, double> operation)
{
Console.WriteLine("Please enter the first number: ");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Please enter the second number: ");
double num2 = Convert.ToDouble(Console.ReadLine());
double res = operation(num1, num2);
Console.WriteLine("RESULT: " + res);
Console.WriteLine("");
Console.ReadLine();
}

Categories

Resources