how will I access the methods into my Switch statement? [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
how do I access the methods??
how do I access the methods??
and use them in Switch statement?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace practise_Delegates_MenuDriven
{
class Program
{
delegate int Converter(int value);
static int ToCel(int fah)
{
return fah;
}
static int ToFah(int celsius)
{
return celsius;
}
static int ToKel(int celsius2)
{
return celsius2;
}
static int ToRank(int celsius3)
{
return celsius3;
}
static void DisplayMenu()
{
Console.WriteLine("Celsius Converter");
Console.WriteLine("=================");
Console.WriteLine("C - Celsius to Fahrenheit");
Console.WriteLine("F - Fahrenheit to Celsius");
Console.WriteLine("K - Celsius to Kelvin");
Console.WriteLine("R - Celsius to Rankine");
Console.WriteLine("X - Exit");
}
static char GetMenuOption(char letter)
{
Console.WriteLine("Please enter C, F, K, R, X: ");
letter = Convert.ToChar(Console.ReadLine());
return letter;
}
static int GetValue(int value)
{
Console.WriteLine("Please enter the value to convert: ");
value = Convert.ToInt32(Console.ReadLine());
return value;
}
static void PrintResult(int fromValue,int result,string fromstring,string toString)
{
Console.WriteLine(fromValue + " " + fromstring + " is " + result + " " + toString);
}
static void Main(string[] args)
{
Converter process = ToCel;
Converter process1 = ToCel;
Converter process2 = ToKel;
Converter process3 = ToKel;
***switch statement? while loop?***
}
}
}

You don't need arguments in GetMenuOption() and GetValue() methods. And here is loop (it is needed if you want to process more than one temperature) with switch:
while (true)
{
DisplayMenu();
var letter = GetMenuOption();
var fromString = String.Empty;
var toString = String.Empty;
if (letter == 'X')
{
break;
}
var fromValue = GetValue();
var result = 0;
switch (letter)
{
case 'C':
fromString = "F";
toString = "C";
result = process(fromValue);
break;
case 'F':
fromString = "C";
toString = "F";
result = process1(fromValue);
break;
case 'K':
fromString = "C";
toString = "K";
result = process2(fromValue);
break;
case 'R':
fromString = "C";
toString = "R";
result = process3(fromValue);
break;
}
PrintResult(fromValue, result, fromString, toString);
}

switch (charValue) {
case 'C':
ToCel(int val);
break;
case 'F':
ToFah(int val);
break;
//rest of the case
default:
Console.WriteLine("invalid value");
break;
}
You need to pass the character input into the switch statement, then you can decide what to do for each different case.
also, why are you passing a char and an int into GetMenuOption and GetValue?
it should be like this, unless you have a good reason
static char GetMenuOption()
{
Console.WriteLine("Please enter C, F, K, R, X: ");
char letter = Convert.ToChar(Console.ReadLine());
return letter;
}
static int GetValue()
{
Console.WriteLine("Please enter the value to convert: ");
int value = Convert.ToInt32(Console.ReadLine());
return value;
}

Related

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.

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

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");
}
}

How can i have a case in a switch statement that lets a user input a string to be displayed

So i've got this code. I have it so that when the user inputs a number 1-4 it will display a different saying plus their name at the beginning based on which number they input. What i want to do is make it so that when they input a -1 instead of 1, 2, 3 or 4 it allows them to type in their own saying to be output.
using System;
namespace TryIt
{
class Conversation
{
// Declare constants that define the input range
private const int MIN = -1;
private const int MAX = 4;
// Declare constants for the colors to be used
private const ConsoleColor INPUT_COLOR = ConsoleColor.Green;
private const ConsoleColor PROMPT_COLOR = ConsoleColor.Blue;
private const ConsoleColor ERROR_COLOR = ConsoleColor.Red;
private const ConsoleColor MESSAGE_COLOR = ConsoleColor.White;
private const ConsoleColor BACKGROUND_COLOR = ConsoleColor.DarkGray;
private String name;
public Conversation()
{
Console.Title = "The Best TryIt Program";
Console.BackgroundColor = BACKGROUND_COLOR;
Console.Clear();
}
public void go()
{
getName();
int number = getNumber();
displayMessage(number);
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine();
}
private void getName()
{
Console.ForegroundColor = PROMPT_COLOR;
Console.Write("Enter your name. ");
Console.ForegroundColor = INPUT_COLOR;
// This will ask what your name is and prompt you to enter it.
name = Console.ReadLine();
}
private int getNumber()
{
int input;
// int input will take your name and display it back to you
do
{
Console.ForegroundColor = PROMPT_COLOR;
Console.Write("\nEnter a number from 1 to 4. ");
Console.ForegroundColor = INPUT_COLOR;
// This will ask you for a number
input = Convert.ToInt16(System.Console.ReadLine());
// If you don't put in a valid number it will tell you
if (input < MIN || input > MAX)
{
Console.ForegroundColor = ERROR_COLOR;
Console.WriteLine("Invalid Number!");
}
} while (input < MIN || input > MAX);
return input;
}
private void displayMessage(int choice)
{
String phrase = " ";
// Declares the variable (a string) for the output messages.
switch (choice)
{
case 1: phrase = " is a genius!"; break;
case 2: phrase = " is amazing!"; break;
case 3: phrase = " came to chew bubblegum" +
", kick butt " + "and is all out of gum."; break;
case 4: phrase = " is a rockstar!"; break;
}
Console.WriteLine();
Console.ForegroundColor = MESSAGE_COLOR;
// This will display the message you selected 10 times
for (int counter = 0; counter < 10; counter++)
{
Console.WriteLine(counter + ") " + name + phrase);
}
}
}
}
switch(choice)
{
case 1: ...
.
.
.
case -1: Console.WriteLine("Put in your own saying: ");
phrase = " " + Console.ReadLine();
break;
}
This switch case will ask you when typing "-1" to put in the saying and then writes it into phrase. After the switch case you can proceed like in your above code.

Where to put my functions so that it can be called from my switch statement?

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);
}
}

Categories

Resources