Hello I am new at this and I Would like to call the function menu in the other case statement so that when i press 1 it directly goes to the case which is labelled groceries.Hopefully I have explained myself thoroughly.
static void menu()
{
Console.WriteLine("Select a category to view");
Console.WriteLine("");
Console.WriteLine("1.Groceries");
Console.WriteLine("2.Electronics & Appliances");
Console.WriteLine("3.Exit");
Console.ReadKey();
int response = int.Parse(Console.ReadLine());
switch (response)
{
case 1:
Console.WriteLine("...........Groceries...............");
break;
case 2:
Console.WriteLine("..............Electronics & Appliances............");
break;
case 3:
Console.WriteLine("...........Exit...............");
break;
}
}
static void Main(string[] args)
{
menu();
Console.WriteLine(#" Choose items being purchased from Groceries /n
1:stove = 3000 \n 2: potcollection = 2000 \n
3:lemonsqeezer = 1000 \n 4:oven = 10000 \n 5:blender = 6000");
double stove = 3000;
double lemonsqeezer = 1000;
double oven = 10000;
double blender = 6000;
double potcollection = 2000;
Console.WriteLine("Enter a number from the above groceries list");
int response = int.Parse(Console.ReadLine());
if (response == 1)
switch (response)
{
case 1:
Console.WriteLine("The total is{0}",);
break;
case 2:
Console.WriteLine("The total is {0}",);
break;
}
}
You always process option 1, because you have an if statement wrapping your switch.
if (response == 1) // no other response other than 1 will get processed.
switch (response)
{
case 1:
Console.WriteLine("The total is{0}",);
break;
case 2:
Console.WriteLine("The total is {0}",);
break;
}
}
Remove the if and the other case statements will get executed.
You're already doing it.
switch (response)
{
case 1:
Console.WriteLine("...........Groceries...............");
You're calling Console.WriteLine from your case. You can call another method or function the same way.
I modified you code:
static void menu()
{
double[] groceries = new double[] { 3000, 1000, 10000, 6000, 2000 }; // By creating an array, you can easily get the price of an item by the index.
// double[] groceries = new double[] { stove, lemonsqeezer, oven, blender, potcollection };
// double[] electronics_and_appliances = new double[] { ... };
Console.WriteLine("Select a category to view");
Console.WriteLine("");
Console.WriteLine("1.Groceries");
Console.WriteLine("2.Electronics & Appliances");
Console.WriteLine("3.Exit");
int response = int.Parse(Console.ReadLine());
switch (response)
{
case 1:
Console.WriteLine("...........Groceries...............");
Console.WriteLine("");
Console.WriteLine(#" Choose items being purchased from Groceries /n
1:stove = 3000 \n 2: potcollection = 2000 \n
3:lemonsqeezer = 1000 \n 4:oven = 10000 \n 5:blender = 6000");
Console.WriteLine("");
Console.WriteLine("Enter a number from the above groceries list");
// This prevents IndexOutOfRangeException.
try
{
Console.WriteLine("The total is {0}", groceries[int.Parse(Console.ReadLine()) - 1]); // Minus one becuase index's start from 0.
}
catch
{
Console.WriteLine("That item doesn't exist");
}
break;
case 2:
Console.WriteLine("..............Electronics & Appliances............");
/*
Console.WriteLine("");
Console.WriteLine(#"Choose items being purchased from Electronics & Appliances/n ...");
Console.WriteLine("");
Console.WriteLine("Enter a number from the above Electronics & Appliances list");
try
{
Console.WriteLine("The total is {0}", electronics_and_appliances[int.Parse(Console.ReadLine()) - 1]);
}
catch
{
Console.WriteLine("That item doesn't exist");
}
*/
break;
case 3:
Console.WriteLine("...........Exit...............");
break;
}
}
static void Main(string[] args)
{
menu();
}
Related
I am making an interface to store character and dinosaur variables to a list and then print them out when asked.
There is a switch statement to take the users' inputs:
Case 1: The function allows the user to input character data and then it's put into a list.
Case 2.: The function allows the user to input dinosaur
data and then it put into a list.
Case 3 The function prints the objects in each list. However, whenever I run it it doesn't print anything and comes up with no errors. If I run the code to print each list in their respective case then they print out fine.
class Program
{
static void Main()
{
int NumAns;
Console.WriteLine("*1. Character Creator ");
Console.WriteLine("*2. Dinosaur Creator ");
Console.WriteLine("*3. Display ");
Console.WriteLine("");
Console.WriteLine("Specify your menu choice");
string NumAnsString = Console.ReadLine();
NumAns = Convert.ToInt32(NumAnsString);
MenuChosen(NumAns);
}
static void MenuChosen(int selection)
{
List<Dinosaur> Dinosaur_l = new List<Dinosaur>();
List<Character> CharSave = new List<Character>();
Character character = new Character();
Dinosaur dinosaur = new Dinosaur();
switch (selection)
{
case 1:
Console.WriteLine("You chose Character Creator");
character.CharacterVal();
CharSave.Add(new Character
{
name = character.name,
age = character.age,
height = character.height,
hair = character.hair,
eyes = character.eyes,
glasses = character.glasses
});
Main();
break;
case 2:
Console.WriteLine("You chose Dinosaurs");
dinosaur.DinoVal();
Dinosaur_l.Add(new Dinosaur
{
name = dinosaur.name,
species = dinosaur.species,
diet = dinosaur.diet,
sex = dinosaur.sex
});
Main();
break;
case 3:
Console.WriteLine(" ");
Console.WriteLine("Character: ");
Console.WriteLine(" ");
foreach (Character chara in CharSave)
{
Console.WriteLine(chara.name);
Console.WriteLine(chara.age);
Console.WriteLine(chara.height);
Console.WriteLine(chara.hair);
Console.WriteLine(chara.eyes);
Console.WriteLine(chara.glasses);
}
Console.WriteLine(" ");
Console.WriteLine("Dinosaurs: ");
Console.WriteLine(" ");
foreach (Dinosaur Dino in Dinosaur_l)
{
Console.WriteLine(Dino.name);
Console.WriteLine(Dino.species);
Console.WriteLine(Dino.diet);
Console.WriteLine(Dino.sex);
}
Console.WriteLine(" ");
Main();
break;
}
}
}
This is the code used for CharacterVal function
public class Character
{
public string name;
public string age;
public string height;
public string hair;
public string eyes;
public string glasses;
public int charID = 0;
int x = 1;
public void CharacterVal()
{
charID++;
Console.WriteLine("Name your Character: ");
name = Console.ReadLine();
Console.WriteLine("How old is " + name + "? :");
age = Console.ReadLine();
Console.WriteLine("How tall is " + name + "?: ");
height = Console.ReadLine();
Console.WriteLine("What colour is " + name + "'s hair ?: ");
hair = Console.ReadLine();
Console.WriteLine("What colour is " + name + "'s eyes ?: ");
eyes = Console.ReadLine();
GlassesCheck();
}
public void GlassesCheck()
{
Console.WriteLine("does " + name + " wear glasses? (yes/no): ");
while (x == 1)
{
glasses = Console.ReadLine();
if(glasses =="yes")
{
x = 2;
}
else if(glasses == "no")
{
x = 2;
}
else
{
x = 1;
Console.WriteLine("'"+glasses+"' is not a valid answer, does " + name + " wear glasses? (yes/no): ");
}
}
}
}
This is the code used for the DinoVal function
public class Dinosaur
{
public string species;
public string diet;
public string sex;
public string name;
public void DinoVal()
{
Console.WriteLine("***************************");
Console.WriteLine("*Choose a Dinosaur *");
Console.WriteLine("* *");
Console.WriteLine("*1. Alvarezsaurus *");
Console.WriteLine("*2. Avimimus *");
Console.WriteLine("*3. Bactrosaurus *");
Console.WriteLine("*4. Baryonyx *");
Console.WriteLine("*5. Coloradisaurus *");
Console.WriteLine("*6. Chungkingosaurus *");
Console.WriteLine("***************************");
int Selection = Convert.ToInt32(Console.ReadLine());
switch (Selection)
{
case 1:
Console.WriteLine("you have chosen the Alvarezsaurus");
Console.WriteLine("This is a Carnivore ");
species = "Alvarezsaurus";
diet = "Carnivore";
break;
case 2:
Console.WriteLine("you have chosen the Avimimus");
Console.WriteLine("This is an Omnivore ");
species = "Avimimus";
diet = "Omnivore";
break;
case 3:
Console.WriteLine("you have chosen the Bactrosaurus");
Console.WriteLine("This is a Herbivore ");
species = "Bactrosaurus";
diet = "Herbivore";
break;
case 4:
Console.WriteLine("you have chosen the Baryonyx");
Console.WriteLine("This is a Carnivore ");
species = "Baryonyx";
diet = "Carnivore";
break;
case 5:
Console.WriteLine("you have chosen the Coloradisaurus");
Console.WriteLine("This is an Omnivore ");
species = "Coloradisaurus";
diet = "Omnivore";
break;
case 6:
Console.WriteLine("you have chosen the Chungkingosaurus");
Console.WriteLine("This is a Herbivore ");
species = "Chungkingosaurus";
diet = "Herbivore";
break;
}
Console.WriteLine("Please choose the dinosaurs sex");
Console.WriteLine("1.Male");
Console.WriteLine("2.Female");
int GenderChoice = Convert.ToInt32(Console.ReadLine());
switch (GenderChoice)
{
case 1:
Console.WriteLine("the dinosaur will be male");
sex = "Male";
break;
case 2:
Console.WriteLine("the dinosaur will be female");
sex = "Female";
break;
}
Console.WriteLine("What name will you give this " + sex + " " + species + " ?:");
name = Console.ReadLine();
}
}
i've tried moving
CharSave.Add(new Character
{
name = character.name,
age = character.age,
height = character.height,
hair = character.hair,
eyes = character.eyes,
glasses = character.glasses
});
into case 3 but all that does is print blank spaces for each object
The lists that store the characters and the dinos need to be outside of the MenuChosen method because as you code is written everytime MenuChosen is called new lists are created.
You could:
class Program
{
static List<Dinosaur> Dinosaur_l = new List<Dinosaur>();
static List<Character> CharSave = new List<Character>();
}
Main -> MenuChosen -> Main -> MenuChosen -> ...
Because the way you structured (Main calls MenuChosen which calls Main and so on) your code - if you run the game for long enough - will get end up with a stack overflow.
To avoid this you can run your code in a loop:
Main()
{
while (true) // or selection was 'Quit', etc.
{
your code here
}
// Remove calls to 'Main' from the switch statement.
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)
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);
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();
}
I am very new in C# programming and I have a problem. I dont know where to put my functions and how to declare them so that I can call them from my switch statement. And will I be able to use my numberarr and wordarr array in my functions or do I also need to create a separate function for it Here is my code:
class Program
{
enum Menu
{
Numbers = 1,
Words = 2,
Exit = 3,
}
static void Main(string[] args)
{
bool isValid;
do
{
isValid = true;
Menu menu = 0;
int number;
string word;
Console.WriteLine("Choose an option from the menu: ");
Console.WriteLine("1. Numbers ");
Console.WriteLine("2. Words ");
Console.WriteLine("3. Exit ");
switch (menu)
{
case Menu.Numbers:
List<int> numberarr = new List<int>();
Console.WriteLine("Please input as many numbers as you like or type exit");
number = int.Parse(Console.ReadLine());
numberarr.Add(number);
break;
case Menu.Words:
List<string> wordarr = new List<string>();
Console.WriteLine("Please input as many numbers as you like");
word = Console.ReadLine();
wordarr.Add(word);
break;
case Menu.Exit:
break;
default:
Console.WriteLine("You have made an invalid selection, try again");
isValid = false;
break;
}
} while (isValid);
}
}
class Choice
{
static void Numbers(int sum, int count, int average, int max, int min)
{
}
static void Words(string[] args)
{
}
static void Exit()
{
}
}
You can't use the methods defined in the Choice class in Main because you haven't declared them with the public identifier. In C# class properties default to being private so unless you explicitly declare them as public only the class itself will know of their existence.
So basically just change all of declarations in Choice from static void MethodName to public static void MethodName and then you will be able to call them in main from the Choice class like;
Choice.Exit();
EDIT: You'll also need to make some changes to make the switch statement work. As pointed out in the comments there is no way for menu to have a value other than 0. I suggest you use something more like the following;
isValid = true;
int menu = 0;
int number;
string word;
Console.WriteLine("What type do you want to use?");
Console.WriteLine("Press 1 for numbers, 2 for words, or 3 exit.");
string input = Console.ReadLine(); // we must read the users input
if (!int.TryParse(input, out menu))
{
// the user didn't enter a number make them try again
// note you might want to use a loop here to ensure the program does not
// proceed until the user has entered "1", "2", or "3"
}
switch (menu)
If I am understanding your question, just place your functions within your class. I've adjusted your code accordingly. You may also have problems with your word/num classes. You normally have to instantiate them but with something like Choice myChoice = new Choice();
Class Program
{
enum Menu
{
Numbers = 1,
Words = 2,
Exit = 3,
}
static void Main(string[] args)
{
bool isValid;
do
{
isValid = true;
Menu menu = 0;
int number;
string word;
Console.WriteLine("Choose an option from the menu: ");
Console.WriteLine("1. Numbers ");
Console.WriteLine("2. Words ");
Console.WriteLine("3. Exit ");
switch (menu)
{
case Menu.Numbers:
List<int> numberarr = new List<int>();
Console.WriteLine("Please input as many numbers as you like or type exit");
number = int.Parse(Console.ReadLine());
numberarr.Add(number);
int retInt = functionGetInt(number)
break;
case Menu.Words:
List<string> wordarr = new List<string>();
Console.WriteLine("Please input as many numbers as you like");
word = Console.ReadLine();
wordarr.Add(word);
string retString = functionGetString(word);
break;
case Menu.Exit:
break;
default:
Console.WriteLine("You have made an invalid selection, try again");
isValid = false;
break;
}
} while (isValid);
private string functionGetString(string pParmString)
{
//code
return "string";
}
private int functionGetInt(int pParmInt)
{
//code
return 0;
}
}
}
EDIT:
For the code you presented here this would be one possibility.I removed the enum,i normally try to deal with the code presented but yes it was not necessary:
class Program
{
//enum Menu
//{
// Numbers = 1,
// Words = 2,
// Exit = 3,
//}
static void Main(string[] args)
{
bool isValid;
do
{
isValid = true;
int menu = 0;
int[] number;
string word;
Console.WriteLine("Choose an option from the menu: ");
Console.WriteLine("1. Numbers ");
Console.WriteLine("2. Words ");
Console.WriteLine("3. Exit ");
string s = Console.ReadLine();
while (!Regex.IsMatch(s, "^[1-3]{1}$"))
{
Console.WriteLine("Please enter a valid choice(1 to 3)");
s = Console.ReadLine();
}
menu = Convert.ToInt32(s);
switch (menu)
{
case 1:
List<int> numberarr = new List<int>();
Console.WriteLine("Please input as many numbers as you like separeted by space or comma,or type exit");
string numbers = Console.ReadLine();
if (numbers == "exit")
Choice.Exit();
else
{
number = numbers.Split(new char[] { ',', ' ' }).Select(x => int.Parse(x)).ToArray();
numberarr.AddRange(number);
Choice.Numbers(numberarr.Sum(), numberarr.Count, numberarr.Average(), numberarr.Max(), numberarr.Min());
}
break;
case 2:
List<string> wordarr = new List<string>();
Console.WriteLine("Please input as many numbers as you like separeted by space or comma");
word = Console.ReadLine();
wordarr.AddRange(word.Split(new char[] { ',', ' ' }));
Choice.Words(wordarr);
break;
case 3:
Choice.Exit();
break;
default:
Console.WriteLine("You have made an invalid selection, try again");
isValid = false;
break;
}
} while (isValid);
Console.ReadKey();
}
}
class Choice
{
public static void Numbers(int sum, int count, double average, int max, int min)
{
int a = sum;
int b = count;
double c = average;
int d = max;
int e = min;
//just as example.
}
public static void Words(List<string> args)
{
//do whatever you need here
}
public static void Exit()
{
Environment.Exit(0);
}
}