Print message when invalid data entered in console application using switch C# - 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();
}

Related

How to accept the user response either as an int, or a char or a string. C#

int number;
do
{
DisplayMenu();
number = Convert.ToInt32(Console.ReadLine()); //here need int, string, and char
if (number < 0 || number > 6)
{
Console.WriteLine("An error occured!");
break;
}
} while (number != 0);
static void DisplayMenu()
{
Console.WriteLine("Main Menu");
Console.WriteLine("1) Calculate Sum ");
Console.WriteLine("2) Calculate Average");
Console.WriteLine("3) Display Numbers");
Console.WriteLine("4) Display Poem");
Console.WriteLine("5) Create Numbers Array");
Console.WriteLine("0) To Exit");
Console.WriteLine();
Console.WriteLine("Enter the number that corresponds to your choice: ");
}
I need to take the user input in integer, string, and character. Moreover, this code should then still work properly.
I was searching on other boards but there is no such thing I could find.
Reading your code, it appears that you are asking the user to enter a single digit from 0-5 to select the next function. One straightforward way of doing this is to substitute the ReadKey() method and switch on the result. As a bonus, the menu will execute immediately without having to wait for the [Enter] key.
// Loop until a valid int is received.
bool exit = false;
while (!exit)
{
DisplayMenu();
switch (Console.ReadKey().Key)
{
case ConsoleKey.D0: exit = true; break;
case ConsoleKey.D1: calculateSum(); break;
case ConsoleKey.D2: calculateAverage(); break;
case ConsoleKey.D3: displayNumbers(); break;
case ConsoleKey.D4: displayPoem(); break;
case ConsoleKey.D5: createNumbersArray(); break;
default:
Console.Clear();
Console.WriteLine("Please enter a number 0-5");
Thread.Sleep(1000);
break;
}
}

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)

Need help Improving Basic C# Calculator [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I made this Basic C# Calculator to reflect on what I've learned these past few days. I'm an absolute beginner and I wanted to get suggestions on improving and shortening it.
I've tried to add switch statements and multiple methods, but it has been really hard grasping them.
using System;
namespace lol
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hi! What is your name?");
string name = Console.ReadLine();
Console.WriteLine(name + " What do you wanna do?");
Console.WriteLine("Type \"+\" for addition");
Console.WriteLine("Type \"-\" for Subraction");
Console.WriteLine("Type \"*\" for Multiplication");
Console.WriteLine("Type \"/\" for division");
string operation = Console.ReadLine();
Console.Write("Now, Give me number one: ");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Now give me number two: ");
double num2 = Convert.ToDouble(Console.ReadLine());
if (operation == "+")
{
Console.WriteLine(num1 + num2);
}
else if (operation == "-")
{
Console.WriteLine(num1 - num2);
}
else if (operation == "*")
{
Console.WriteLine(num1 * num2);
}
else
{
Console.WriteLine(num1 / num2);
}
}
}
}
If it better for your eyes, you can write like that:
static class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hi! What is your name?");
string name = Console.ReadLine();
Console.WriteLine(name + " What do you wanna do?");
string[] operations = new string[] { "\"+\" for addition", "\"-\" for subtraction", "\"*\" for multiplication", "\"/\" for divsion" };
foreach (string operation in operations) { Console.WriteLine("Type " + operation); }
string cmd = Console.ReadLine();
Console.Write("Now, Give me number one: ");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Now give me number two: ");
double num2 = Convert.ToDouble(Console.ReadLine());
switch (cmd)
{
case "+": Console.WriteLine(num1 + num2); break;
case "-": Console.WriteLine(num1 - num2); break;
case "*": Console.WriteLine(num1 * num2); break;
case "/": Console.WriteLine(num1 / num2); break;
}
}
}
Using enums and checking if the user input is valid. I also added a loop that checks if the user wants to input equations.
References:
double.TryParse
Enum
Switch Case
You can try it here: https://dotnetfiddle.net/aIwX5P
using System;
public class Program
{
enum eOperator
{
opAdd = 0,
opSub = 1,
opDiv = 2,
opMul = 3,
opInvalid = int.MinValue + 1,
opQuit = int.MinValue
}
public static void Main()
{
double a = 0.0, b = 0.0;
eOperator op = eOperator.opQuit;
string input = String.Empty;
Console.WriteLine("Calculator");
Console.WriteLine("Enter 'quit' at any time to exit.");
// repeat until the user wants to quit.
do // while(op != eOperator.opQuit)
{
Console.Write("a = ");
input = Console.ReadLine().ToLower().Trim();
if (double.TryParse(input, out a))
{
// input is a valid double and was stored in a
Console.Write("Operator: ");
input = Console.ReadLine().ToLower().Trim();
switch (input)
{
case "+":
op = eOperator.opAdd;
break;
case "-":
op = eOperator.opSub;
break;
case "*":
op = eOperator.opMul;
break;
case "/":
op = eOperator.opDiv;
break;
case "quit":
op = eOperator.opQuit;
break;
default:
op = eOperator.opInvalid; // can't be left as quit
Console.WriteLine("Invalid entry. +, -, *, / or quit for operator.");
break;
}
if (op != eOperator.opQuit && op != eOperator.opInvalid)
{
// user didn't choose to quit or type something invalid
Console.Write("b = ");
input = Console.ReadLine().ToLower().Trim();
if (double.TryParse(input, out b))
{
// input is a valid double and was parsed into b
double result = a; // we use the operator on a, so we might as well just store a into the result right away.
// do the operation on result.
switch (op)
{
case eOperator.opAdd:
result += b;
break;
case eOperator.opSub:
result -= b;
break;
case eOperator.opMul:
result *= b;
break;
case eOperator.opDiv:
// Div by 0 check. without this, this still works since double has +/- inf values.
if (b != 0.0) // comparing double with = and != is usually bad idea, but 0.0 is saved without rounding errors.
{
result /= b;
}
else
{
Console.WriteLine("Div by 0");
op = eOperator.opInvalid;
}
break;
default:
// this if branch checked for the other two operators. since we never chanced op after that check, this exception should never happen.
// it is still a good idea to include it to find errors in your logic, should they have occurred.
throw new Exception("This shouldn't happen.");
}
if (op != eOperator.opInvalid)
{
Console.WriteLine("Result: " + result.ToString());
}
// the only invalid operation is div by 0 for now. the message was sent to the user in that case, so no else is needed at this point.
// alternatively you can store an error message into a string, and when op = opInvalid, then display that error message here centralized.
// this would be a good idea if multiple things can go wrong.
}
else if (input == "quit")
{
// input for b was an invalid number, but input was 'quit'
op = eOperator.opQuit;
}
else
{
// input for b was an invalid number and also not 'quit', display error message
Console.WriteLine("Invalid entry. Type a number or Quit");
}
}
}
else if (input == "quit")
{
// input for a was invalid number, but 'quit'
op = eOperator.opQuit;
}
else
{
// input for a was invalid number and also not 'quit'
Console.WriteLine("Invalid entry. Type a number or Quit");
}
// repeat until the user wants to quit.
}while(op != eOperator.opQuit);
Console.WriteLine("Bye");
}
}

Pseudocode for switch statement in c#

How do I write the pseudocode for a switch (case) statement in C#?
switch (option)
{
case 1:
Console.Write("Enter First Number: ");
num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter Second Number: ");
num2 = Convert.ToDouble(Console.ReadLine());
result = num1 + num2;
Console.WriteLine(result);
break;
case 2:
Console.Write("Enter First Number: ");
num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter Second Number: ");
num2 = Convert.ToDouble(Console.ReadLine());
result = num1 - num2;
Console.WriteLine(result);
break;
case 3:
Console.Write("Enter First Number: ");
num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter Second Number: ");
num2 = Convert.ToDouble(Console.ReadLine());
result = num1 * num2;
Console.WriteLine(result);
break;
default:
Console.WriteLine("\n Next time follow instructions. You can only choose numbers 1 - 4");
break;
}
So, if I was going to write this, I'd start with an enumerated type for the operations:
public enum ArithmeticOperation
{
Add,
Subtract,
Multiply,
Divide,
}
I'd write a little helper function:
private static string ShowEnumOptions<T>() where T : struct
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException($"Type: {typeof(T).ToString()} must be an enumerated type");
}
var options = Enum.GetNames(typeof(T));
return string.Join("/", options);
}
(the newest version of C# (which I don't use yet) allows a System.Enum constraint on a generic type parameter which would simplify this)
Then I'd write my main program to look like this:
static void Main(string[] args)
{
while (true)
{
ArithmeticOperation operation = default(ArithmeticOperation);
var goodOperation = false;
while (!goodOperation)
{
Console.Write(
$"Enter operation (one of [{ShowEnumOptions<ArithmeticOperation>()}] or \"Quit\"): ");
var response = Console.ReadLine();
if (string.Equals(response, "Quit", StringComparison.InvariantCultureIgnoreCase))
{
return; //quit the app
}
if (Enum.TryParse<ArithmeticOperation>(response, true, out operation))
{
goodOperation = true;
}
}
double value1 = 0.0;
double value2 = 0.0; //initialize them to keep the compiler happy
var goodDouble = false;
while (!goodDouble)
{
Console.Write("Enter the first number: ");
var response = Console.ReadLine();
if (double.TryParse(response, out value1))
{
goodDouble = true;
}
}
goodDouble = false;
while (!goodDouble)
{
Console.Write("Enter the second number: ");
var response = Console.ReadLine();
if (double.TryParse(response, out value2))
{
goodDouble = true;
}
}
//ok, got an operation and two numbers
double result = 0.0;
switch (operation)
{
case ArithmeticOperation.Add:
result = value1 + value2;
break;
case ArithmeticOperation.Subtract:
result = value1 - value2;
break;
case ArithmeticOperation.Multiply:
result = value1 * value2;
break;
case ArithmeticOperation.Divide:
if (value2 == 0.0)
{
Console.WriteLine("Division by zero is invalid");
result = double.NaN; //NaN means "not a number"
break;
}
result = value1 / value2;
break;
}
Console.WriteLine($"Result is {result}");
}
}
Note that I check all input for validity. Always assume your users will enter bad data. Also note that I check my double for equality with zero. Checking for floating point equality is usually a bad idea, but it's the right thing to do here.
Then, as pseudo code, all I'd write would be:
// Get the operation (one of add/subtract/multiply or divide) - or allow the user to quit
// Get each of value1 and value2 as doubles
// Based on the operation, calculate the result (pay attention to division by zero)
// Show the result
// Loop back and let the user try again (or quit)
Pseudocode is basically writing what you're trying to do in comments. What your professor was probably trying to teach you is to make a bunch of comments to plan out the structure of your code, and then write your code. What you have above is already functional code. At the risk of answering your homework question, I'd say it goes something like this:
switch(option)
{
case 1:
//do something
break;
case 2:
//do something else
break;
default:
//what to do if none of the cases are met
break;
}
I don't know what you mean with pseudocode but this code is less repetitive:
double result = 0;
Console.Write("Enter First Number: ");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter Second Number: ");
double num2 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter a number from 1 to 3");
string input = Console.ReadLine();
switch (input) {
case "1" :
result = num1 + num2;
break;
case "2":
result = num1 - num2;
break;
case "3":
result = num1 * num2;
break;
default:
Console.WriteLine("\n Next time follow instructions. You can only choose numbers 1 - 4");
break;
}
Console.WriteLine("Result = " + result);

Entered wrong value. goto Start;

Edit.
Based on the answers received I realized that I am asking more than I know about at this early stage in my learning and as such, I have decided to forget this question until I have learnt and understand more. I do not want to overstep and confuse myself.
Just a newbie looking for some guidance.
From a previous question I asked here, I was introduced to the goto Start; in the switch statement.
I started using it and it had me thinking that I wanted the program to go to the start in the event the user entered an invalid input. Example, in my calculator below, if the user enters something other than a number, how do I get the program to disregard the input and prompt the user again to enter a number? Maybe even display an "invalid input. please try again" to the user.
Right now, if anything but a number is entered, the console crashes and throws me an error.
Thanks in advance for the assistance
int num1, num2, output;
string op;
Console.Write("\n\n");
Console.WriteLine("Calculator\n");
Console.WriteLine("=============");
Console.Write("\n\n");
Start:
Console.Write("Please enter first number:");
num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter second number: ");
num2 = Convert.ToInt32(Console.ReadLine());
Operator:
Console.WriteLine("Please select operator: ");
Console.WriteLine("\nAddition : +");
Console.WriteLine("Multiplication: *");
Console.WriteLine("Division: /");
Console.WriteLine("Subtraction: -");
Console.Write("Enter Operator: ");
op = Console.ReadLine();
switch (op)
{
case "+":
output = num1 + num2;
Console.WriteLine("{0} added to {1} = {2}", num1, num2, output);
break;
case "*":
output = num1 * num2;
Console.WriteLine("{0} multiplied by {1} = {2}", num1, num2, output);
break;
case "/":
if (num2 == 0)
{
Console.WriteLine("Cannot divide by zero. Please try again");
goto Start;
}
else
{
output = num1 / num2;
Console.WriteLine("{0} divided by {1} = {2}", num1, num2, output);
break;
}
case "-":
output = num1 - num2;
Console.WriteLine("{0} minus{1} = {2}", num1, num2, output);
break;
default:
Console.WriteLine("You entered an invalid operator. Please try again\n");
goto Operator;
}
Console.WriteLine("\nPress enter to continue....");
Console.ReadLine();
Please, whatever you do, do NOT use goto. Ever. Maybe except in switch to fall down to other case, but even that should be very rare. It makes your code unreadable, confusing and hard to maintain. Please see spaghetti code.
That said, you should do Int32.TryParse instead of Convert if you are not sure if the input is valid:
int num1;
do
{
Console.Write("Please enter first number:");
} while (!Int32.TryParse(Console.ReadLine(), out num1));
And change your switch to something like this (to avoid goto):
bool inputOk = false;
while (!inputOk)
{
Console.WriteLine("Please select operator: ");
//...
op = Console.ReadLine();
inputOk = true;
switch (op)
{
//...
default:
Console.WriteLine("You entered an invalid operator. Please try again\n");
inputOk = false;
break;
}
}
Untested, but this may be what you want:
Start:
Console.Write("Please enter first number:");
if (!int.TryParse(Console.ReadLine(), out num1))
goto Start;
//num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter second number: ");
num2 = Convert.ToInt32(Console.ReadLine());
Operator:
...
And perhaps the same for num2, if you need.
The best way to achieve this is through the use of EXCEPTION. Since you are learning, I would not provide a sample code on how to do it but would want you to read about it here and here
goto inside a switch tries to go to the defined case. In your example there is no start case so it doesn't know where to go.
more info here.
I would suggest using methods though.
I don't think goto statements are suitable in this situation. Your code can get really messy if you have a lot of them. Using FormatException isn't recommended either, since throwing an exception takes a long time.
I think you should use Int32.TryParse instead.
Here's a piece of sample code. See if you can apply this to your program.
int input;
while(true) {
Console.WriteLine("Please enter a number");
bool succeeds = Int32.TryParse(Console.ReadLine(), out input);
if (!succeeds) {
Console.WriteLine("Input Invalid! Try again!");
} else {
break;
}
}
// make use of input here
int num1, num2, output;
string op;
Console.Write("\n\n");
Console.WriteLine("Calculator\n");
Console.WriteLine("=============");
Console.Write("\n\n");
Start:
do
{
Console.Write("Please enter valid first number:");
} while (!int.TryParse(Console.ReadLine(), out num1));
do
{
Console.Write("Please enter valid second number:");
} while (!int.TryParse(Console.ReadLine(), out num2));
Operator:
Console.WriteLine("Please select operator: ");
Console.WriteLine("\nAddition : +");
Console.WriteLine("Multiplication: *");
Console.WriteLine("Division: /");
Console.WriteLine("Subtraction: -");
Console.Write("Enter Operator: ");
op = Console.ReadLine();
switch (op)
{
case "+":
output = num1 + num2;
Console.WriteLine("{0} added to {1} = {2}", num1, num2, output);
break;
case "*":
output = num1 * num2;
Console.WriteLine("{0} multiplied by {1} = {2}", num1, num2, output);
break;
case "/":
if (num2 == 0)
{
Console.WriteLine("Cannot divide by zero. Please try again");
goto Start;
}
else
{
output = num1 / num2;
Console.WriteLine("{0} divided by {1} = {2}", num1, num2, output);
break;
}
case "-":
output = num1 - num2;
Console.WriteLine("{0} minus{1} = {2}", num1, num2, output);
break;
default:
Console.WriteLine("You entered an invalid operator. Please try again\n");
goto Operator;
}
Console.WriteLine("\nPress enter to continue....");
Console.ReadLine();

Categories

Resources