I'm a complete noob at programming and I was wondering where i went wrong with this simple calculator i was trying. I can't seem to get the program to run the method. I think it may ave something to do with how i expressed it in the if statement but no matter what i try, i just can't seem to get it to work.
namespace NewNew
{
class Program
{
private static double Ans;
private static double num1;
private static double num2;
private static string op;
static void Main(string[] args)
{
Console.Write("Enter First Number: ");
double num1 = Convert.ToDouble(Console.ReadLine());
string op = Console.ReadLine();
if (op == "+" || op == "-" || op == "/" || op == "*")
{
Calc;
}
else
{
Console.WriteLine("Invalid Operator");
}
Console.WriteLine(Ans);
Console.ReadLine();
}
static double Calc(double Ans)
{
Console.Write("Enter Second Number: ");
double num2 = Convert.ToDouble(Console.ReadLine());
if (op == "+")
{
Ans = num1 + num2;
}
else if (op == "-")
{
Ans = num1 - num2;
}
else if (op == "/")
{
Ans = num1 / num2;
}
else if (op == "*")
{
Ans = num1 * num2;
}
return Ans;
}
}
Alright I see where you were going but seems like you got off track.
You declared all of these as global:
private static double Ans;
private static double num1;
private static double num2;
private static string op;
Each time you re-declared new variables for each with the same name. You never used those existing, static variables.
double num1 = Convert.ToDouble(Console.ReadLine());
string op = Console.ReadLine();
I think this is what you were after:
namespace NewNew
{
class Program
{
private static double Ans;
private static double num1;
private static double num2;
private static string op;
static void Main(string[] args)
{
Console.Write("Enter First Number: ");
num1 = Convert.ToDouble(Console.ReadLine());
op = Console.ReadLine();
if (op == "+" || op == "-" || op == "/" || op == "*")
{
Calc();
}
else
{
Console.WriteLine("Invalid Operator");
}
Console.WriteLine(Ans);
Console.ReadLine();
}
static double Calc()
{
Console.Write("Enter Second Number: ");
num2 = Convert.ToDouble(Console.ReadLine());
if (op == "+")
{
Ans = num1 + num2;
}
else if (op == "-")
{
Ans = num1 - num2;
}
else if (op == "/")
{
Ans = num1 / num2;
}
else if (op == "*")
{
Ans = num1 * num2;
}
return Ans;
}
}
}
Though, I would recommend using local variables vs using them globally across the entire class.
Try passing num1 to your call to Calc:
if (op == "+" || op == "-" || op == "/" || op == "*")
{
Calc(num1);
}
Additionally, you should name the parameter in Calc to num1 instead of Ans, so you can reference its value in the Calc method:
static double Calc(double num1)
{
// ...
}
Method calls require parenthesises after its name e.g MethodName(). In this case you also need to pass a double e.g Calc(2.2) because you specify that in the method definition
first of all, I correct your naming convention for best practices always camel case for local variable name and name your variable properly so it will easy for you to read. you may learn on this link for naming convention https://github.com/ktaranov/naming-convention/blob/master/C%23%20Coding%20Standards%20and%20Naming%20Conventions.md
Second make sure you use your declared variables, because in your code you didn't use these variable:
private static double Ans;
private static double num1;
private static double num2;
private static string op;
and you declare another so that's why you got confuse.
I rewrite your code to more readable code so it will easy to you to understand. But this was a good start keep on writing a code. Be a happy coder :)
private static double answer;
private static double firstNumber;
private static double secondNumber;
private static string operation;
static void Main(string[] args)
{
Console.Write("Enter First Number: ");
firstNumber = Convert.ToDouble(Console.ReadLine());
operation = Console.ReadLine();
if (operation == "+" || operation == "-" || operation == "/" || operation == "*")
{
Calc();
}
else
{
Console.WriteLine("Invalid Operator");
}
Console.WriteLine(answer);
Console.ReadLine();
}
static double Calc()
{
Console.Write("Enter Second Number: ");
secondNumber = Convert.ToDouble(Console.ReadLine());
if (operation == "+")
{
answer = firstNumber + secondNumber;
}
else if (operation == "-")
{
answer = firstNumber - secondNumber;
}
else if (operation == "/")
{
answer = firstNumber / secondNumber;
}
else if (operation == "*")
{
answer = firstNumber * secondNumber;
}
return answer;
}
Change your method as below
static void Calc()
{
Console.Write("Enter Second Number: ");
num2 = Convert.ToDouble(Console.ReadLine());
if (op == "+")
{
Ans = num1 + num2;
}
else if (op == "-")
{
Ans = num1 - num2;
}
else if (op == "/")
{
Ans = num1 / num2;
}
else if (op == "*")
{
Ans = num1 * num2;
}
}
in your main method add parenthesis in your function call and remove the re declaration of variables
static void Main(string[] args)
{
Console.Write("Enter First Number: ");
num1 = Convert.ToDouble(Console.ReadLine());
op = Console.ReadLine();
if (op == "+" || op == "-" || op == "/" || op == "*")
{
Calc();
}
else
{
Console.WriteLine("Invalid Operator");
}
Console.WriteLine(Ans);
Console.ReadLine();
}
Related
How do I return a string from a Int method? Please see my code below. In the last method I would like to print the string "Invalid Operator" if the use keyed in a wrong operator
static void Main(string[] args)
{
Console.WriteLine("Welcome to the simple calculator");
Console.WriteLine("-------------");
Console.WriteLine("Enter the first number");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the Second number");
int num2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Select the Operator");
Console.WriteLine("Key in on of the following numbers:\n" + "1 to add \n" + "2 to subtract \n" + "3 to multiply \n" + "4 to divide");
int op = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your result is");
Console.WriteLine("---------------");
Console.WriteLine(GetResult(num1, num2, op));
Console.ReadLine();
}
I would like the below method to return both the String and Int values
static int GetResult(int a, int b, int c)
{
int result;
if (c == 1)
{
result = a + b;
}
else if (c == 2)
{
result = a - b;
}
else if (c == 3)
{
result = a * b;
}
else if (c == 4)
{
result = a / b;
}
else
{
result = "Invalid Operator";
}
return result;
}
You could use tuples, but I think an exception would be better here, e.g.
static int GetResult(int operatorCode, int operand1, int operand2) =>
operatorCode switch
{
1 => operand1 + operand2,
2 => operand1 - operand2,
3 => operand1 * operand2,
4 => operand1 / operand2,
_ => throw new ArgumentOutOfRangeException(nameof(operatorCode), $"operatorCode {operatorCode} is not valid.")
};
I would recommend exceptions to handle invalid input.
However, you could also do one of these things:
Option 1: Value Tuple
static (int?, string) GetResult(int a, int b, int c)
{
int? result = null;
string error = null;
if (c == 1)
{
result = a + b;
}
else if (c == 2)
{
result = a - b;
}
else if (c == 3)
{
result = a * b;
}
else if (c == 4)
{
result = a / b;
}
else
{
error = "Invalid operator";
}
return (result, error);
}
Option 2: Enum
public enum OperatorCode
{
Add,
Sub,
Mul,
Div
}
static int GetResult(OperatorCode operatorCode, int operand1, int operand2) =>
operatorCode switch
{
OperatorCode.Add => operand1 + operand2,
OperatorCode.Sub => operand1 - operand2,
OperatorCode.Mul => operand1 * operand2,
OperatorCode.Div => operand1 / operand2,
};
This second option doesn't require an error message, because only valid operator codes can be passed to the method.
You can try this
'''
using System;
namespace example
{
public static class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to the simple calculator");
Console.WriteLine("-------------");
Console.WriteLine("Enter the first number");
int num1 = Convert.ToInt32(Console.ReadLine());;
Console.WriteLine("Enter the Second number");
int num2 = Convert.ToInt32(Console.ReadLine());;
Console.WriteLine("Select the Operator");
Console.WriteLine("Key in on of the following numbers:\n" + "1 to add \n" + "2 to subtract \n" + "3 to multiply \n" + "4 to divide");
int op = Convert.ToInt32(Console.ReadLine());;
GetResult(num1, num2, op);
}
static void Invalid()
{
Console.WriteLine("Invalid Operator, Try Again");
}
static void GetResult(int a, int b, int c)
{
int result;
string pref = "Your result is: ";
if (c == 1)
{
result = a + b;
Console.WriteLine(pref+result);
}
else if (c == 2)
{
result = a - b;
Console.WriteLine(pref+result);
}
else if (c == 3)
{
result = a * b;
Console.WriteLine(pref+result);
}
else if (c==4)
{
result = a / b;
Console.WriteLine(pref+result);
}
else
{
Invalid();
}
}
}
}
You could change the return type from int to object
static object GetResult(int a, int b, int c)
{
object result;
if (c == 1)
{
result = a + b;
}
else if (c == 2)
{
result = a - b;
}
else if (c == 3)
{
result = a * b;
}
else if (c == 4)
{
result = a / b;
}
else
{
result = "Invalid Operator";
}
return result;
}
I have never used objects for big projects. It is better to know the return type.
Or you could print while doing the operation. make the method void.
Console.WriteLine(a +b);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I want to be able to store the answer of the last calculation e.g. 2+4=6, and then apply another calculation to the answer? e.g. ans*2=12
namespace calculator2
{
class KPcalculator
{
static void Main(string[] args)
{
// Since i want the calculator to be able to restart I enclose the program in a while loop
ConsoleKeyInfo keyInfo;
bool loop = true;
while (loop)
{
// Declaring my variables
double num1, num2;
string operation;
// Asking the user for the operation, to call a function to perform that operation
Console.Write("\nPlease enter an operation you wish to perform (+, -, /, *, ^, ^1/2, !, f-1, log, rad): ");
operation = Console.ReadLine();
// Prompting the input of the first number
Console.Write("Please enter your first number: ");
num1 = Convert.ToDouble(Console.ReadLine());
// Prompting the input of the second number
Console.Write("Please enter your second number (if no other number is needed please press 0): ");
num2 = Convert.ToDouble(Console.ReadLine());
// Using if statements to decide which function to call based on the operation, as well as an error message for an invalid value
if (operation == "+")
{
Console.WriteLine(Sum(num1, num2));
}
else if (operation == "-")
{
Console.WriteLine(Minus(num1, num2));
}
else if (operation == "/")
{
Console.WriteLine(Divide(num1, num2));
}
else if (operation == "*")
{
Console.WriteLine(Multi(num1, num2));
}
else if (operation == "^")
{
Console.WriteLine(ToPower(num1, num2));
}
else if (operation == "^1/2")
{
Console.WriteLine(Sqroot(num1));
}
else if (operation == "!")
{
Console.WriteLine(Factorial(num1));
}
else if (operation == "f-1")
{
Console.WriteLine(ToInverse(num1));
}
else if (operation == "log")
{
Console.WriteLine(ToLog(num1));
}
else if (operation == "rad")
{
Console.WriteLine(ToRadian(num1));
}
else
{
Console.WriteLine("Invalid operation");
}
// Function for addition (Sum)
static double Sum(double num1, double num2)
{
double resultofSum = num1 + num2;
return resultofSum;
}
// Function for subtraction (Minus)
static double Minus(double num1, double num2)
{
double resultofMinus = num1 - num2;
return resultofMinus;
}
// Function for division (Divide)
static double Divide(double num1, double num2)
{
double resultofDivide = num1 / num2;
return resultofDivide;
}
// Function for multiplication (Multi)
static double Multi(double num1, double num2)
{
double resultofMulti = num1 * num2;
return resultofMulti;
}
// Function for raising x (num1) to the power of y (num2)
static double ToPower(double num1, double num2)
{
double resultofToPower = Math.Pow(num1, num2);
return resultofToPower;
}
// Function for square root of x (num1)
static double Sqroot(double num1)
{
double resultofSqroot = Math.Sqrt(num1);
return resultofSqroot;
}
// Function for finding factorial of x (num1),
static double Factorial(double num1)
{
double factorial = 1;
if (num1 < 0)
{
Console.WriteLine("Error: Can't find factorial of a negative number");
return 0;
}
else if (num1 <= 1)
{
return 1;
}
else
{
for (double i = 1; i <= num1; i++)
{
factorial = factorial * i;
}
Console.WriteLine("{0}! = {1}", num1, factorial);
return factorial;
}
}
// Function for obtaining the inverse of x (1/num1)
static double ToInverse(double num1)
{
double ToInverse = 1 / num1;
return ToInverse;
}
// Function for obtaining the base 10 log of x (num1)
static double ToLog(double num1)
{
double Tolog = Math.Log10(num1);
return Tolog;
}
// Function for converting an angle x (num1) from degrees to radians
static double ToRadian(double num1)
{
double Toradian = (num1 * (Math.PI)) / 180;
return Toradian;
}
// Prompting the user for whether they want to perform another calculation or want to end the program
Console.WriteLine("Do you want to perform another calculation? (Y/N)");
keyInfo = Console.ReadKey();
// The loop ends if N is selected
if (keyInfo.Key == ConsoleKey.N)
{
loop = false;
}
else if (keyInfo.Key == ConsoleKey.Y)
{
loop = true;
}
}
}
}
}
1 - Declare another variable in the Variable Declaration section that you already have in your code.
2 - After Console.WriteLine("{0}! = {1}", num1, factorial);
save the answer into your new dedicated variable.
3 - Use your dedicated variable
kill yourself
as required in your code.
I'm trying to make a fully functioning calculator application for a school assignment. To do that though I need to use try-catch to handle the DivideByZero error this is my code right now:
try
{
Console.WriteLine("Type 1st number: ");
num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("type 2nd number: ");
num2 = Convert.ToInt32(Console.ReadLine());
Console.Write("type operation( x , / , +, -, Fs) ");
operation = Console.ReadLine();
}
catch(DivideByZeroException)
{
Console.WriteLine("Sorry moron you can't divide by zero");
}
but it's not working. It seems to make my code at the top invalid. Does anybody know how to format it properly?
P.S. Full code here:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Calculator_MK._2
{
class Program
{
static void Main(string[] args)
{
Calculator();
}
private static void Calculator()
{
decimal num1;
decimal num2;
string operation;
decimal result;
decimal num3;
decimal num4;
Console.WriteLine("This is IK's Calculator program that should work if you do everything I say");
Console.ReadLine();
try
{
Console.WriteLine("Type 1st number: ");
num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("type 2nd number: ");
num2 = Convert.ToInt32(Console.ReadLine());
Console.Write("type operation( x , / , +, -, Fs) ");
operation = Console.ReadLine();
}
catch(DivideByZeroException)
{
Console.WriteLine("Sorry moron you can't divide by zero");
}
if (operation == "x")
{
result = num1 * num2;
Console.WriteLine("{0} * {1} = {2}", num1, num2, result);
Console.ReadLine();
}
else if (operation == "/")
{
result = num1 / num2;
Console.WriteLine("{0} / {1} = {2}", num1, num2, result);
Console.ReadLine();
}
else if (operation == "+")
{
result = num1 + num2;
Console.WriteLine("{0} + {1} = {2}", num1, num2, result);
Console.ReadLine();
}
else if (operation == "-")
{
result = num1 - num2;
Console.WriteLine("{0} - {1} = {2}", num1, num2, result);
Console.ReadLine();
}
else if (operation == "Fs")
{
int a = 0;
int b = 1;
int c = 1;
Console.WriteLine(a);
Console.WriteLine(b);
for (; c <= 34; c = a + b)
{
Console.WriteLine(c);
a = b;
b = c;
Console.WriteLine();
}
}
if (num2 == 0)
{
Console.WriteLine("Can't divide by zero fool");
}
}
}
}
The try block has to be around the code that causes the exception, in your case this is
result = num1 / num2;
But it would be better to check there for 0 before you call this line and therefore avoid the exception.
The problem you have is that you have declared the try/catch in the wrong place in the application:
try
{
Console.WriteLine("Type 1st number: ");
num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("type 2nd number: ");
num2 = Convert.ToInt32(Console.ReadLine());
Console.Write("type operation( x , / , +, -, Fs) ");
operation = Console.ReadLine();
}
catch(DivideByZeroException)
{
Console.WriteLine("Sorry moron you can't divide by zero");
}
All that is going on here are string to number conversions. There are no mathematical operations that could result in DivideByZeroException exceptions.
Instead, you could wrap the divide operation and anything after it you don't want to run if there is an exception:
else if (operation == "/")
{
try
{
result = num1 / num2;
Console.WriteLine("{0} / {1} = {2}", num1, num2, result);
Console.ReadLine();
}
catch (DivideByZeroException)
{
Console.WriteLine("Sorry moron you can't divide by zero");
}
}
That said, it is not a good practice to allow exceptions to happen in C# if they can be avoided. In this case, you only need to check the divisor to ensure it is not zero to avoid an exception from occurring.
else if (operation == "/")
{
if (num2 != 0)
{
result = num1 / num2;
Console.WriteLine("{0} / {1} = {2}", num1, num2, result);
Console.ReadLine();
}
else
{
Console.WriteLine("Sorry moron you can't divide by zero");
}
}
You have to try the operation itself and not the selection of the operation:
else if (operation == "/")
{
try
{
result = num1 / num2;
Console.WriteLine("{0} / {1} = {2}", num1, num2, result);
Console.ReadLine();
}
catch(DivideByZeroException ex)
{
Console.WriteLine("Sorry moron you can't divide by zero");
}
}
Right now you try to read inputs from the User. If the user inputs something wrong whichc would throw an exception, your try block would trigger but the catch wont, because you are looking for a DivideByZeroException, which wont occur by input
these are the variables I used to save data in
int num1 = int.Parse(Console.ReadLine());
string sign = Console.ReadLine();
int num2 = int.Parse(Console.ReadLine());
the if statement that check the input's
how to make it simple
if (sign == "+")
{
Console.WriteLine(num1 + num2);
}
else if (sign == "-")
{
Console.WriteLine(num1 - num2);
}
else if (sign == "*")
{
Console.WriteLine(num1 * num2);
}
else if (sign == "/")
{
Console.WriteLine(num1 / num2);
}
else
{
Console.WriteLine("Wrong operation sign ...");
}
Console.ReadLine();
How to show the output in the form num1 sign num2 = num3 e.g. "6 + 4 = 10" in the console window?
Use string formatting:
Console.WriteLine("{0} {1} {2} = {3}",num1, sign, num2, num1 + num2);
For more information take a look at: Composite Formatting and also Console.WriteLine(String, Object) Method
Save your result to a variable outside of your if/else statement so that you can "dynamically" build your output at the end.
var result = 0;
if (sign == "+")
{
result = num1 + num2;
}
else if (sign == "-")
{
result = num1 - num2;
}
else if (sign == "*")
{
result = num1 * num2;
}
else if (sign == "/")
{
result = num1 / num2;
}
else
{
Console.WriteLine("Wrong operation sign ...");
}
Console.WriteLine("{0}{1}{2}={3}", num1, sign, num2, result);
Console.ReadLine();
To print out the result u can do
Console.WriteLine("{0}{1}{2}={3}", num1, sign, num2, result)
where result is the result of the operation. (e.g. 6 in your example)
"how to make it simple?"
You can abuse the DataTable.Compute method:
var answer = new DataTable().Compute(num1.ToString() + sign + num2.ToString(), null);
"How to show the output..."
See String.Format / console.WriteLine overload as mentioned by Selman22, eg:
Console.WriteLine("{0} {1} {2} = {3}",num1, sign, num2, answer);
How your program could be written:
Console.WriteLine("Please type a simple sum:");
string sum = Console.Readline();
var answer = new DataTable().Compute(sum, null);
Console.WriteLine("{0} = {1}",sum, answer);
Console.Readline();
Hi it is just a simple calculator. I want to allow user to enter "N" or "n" after I asked them if they want to make an another conversion.
(Enter Y to make an another conversion/Enter N return to Main menu). How do I do that?
static int LengthCalculator() {
int LengthCalculatorOption;
string AnotherConversion = null;
double Centimetres = 0.0, Feet = 0.0, Inches = 0.0, TotalInches = 0.0;
const double CENTIMETRES_PER_INCH = 2.54, INCHES_PER_FOOT = 12;
do {
LengthCalculatorMenu();
LengthCalculatorOption = ValidLengthCalculatorReadOption();
if (LengthCalculatorOption == 1) {
Console.WriteLine("Please Enter the Centimetres(cm) that you wish to convert to feet and inches:");
Centimetres = double.Parse(Console.ReadLine());
TotalInches = (Centimetres / CENTIMETRES_PER_INCH); // This will take a floor function of Centimetres/2.54
Feet = (TotalInches - TotalInches % INCHES_PER_FOOT) / INCHES_PER_FOOT; // This will make it divisible by 12
Inches = TotalInches % INCHES_PER_FOOT; // This will give you the remainder after you divide by 12
Console.WriteLine("\nThe equivalent in feet and inches is {0} ft {1} ins", Feet, Inches);
Console.Write("\nWould you like to make an another conversion? \n\n(Enter Y to make an another conversion/Enter any key return to Main menu):");
AnotherConversion = Console.ReadLine();
} else if (LengthCalculatorOption == 2) {
Console.WriteLine("Please Enter the Feet:");
Feet = double.Parse(Console.ReadLine());
Console.WriteLine("Please Enter the Inches:");
Inches = double.Parse(Console.ReadLine());
Centimetres = ((Feet * INCHES_PER_FOOT) + Inches) * CENTIMETRES_PER_INCH;
Console.WriteLine("\nThe equivalent in centimetres is {0}cm", Centimetres);
Console.Write("\nWould you like to make an another conversion? \n\n(Enter Y to make an another conversion/Enter any key return to Main menu):");
AnotherConversion = Console.ReadLine();
}
} while (AnotherConversion == "y" || AnotherConversion == "Y");
return LengthCalculatorOption;
}//End LenthCalculator
static void LengthCalculatorMenu() {
string LengthCalculatorMenu = ("Enter 1) Convert Centimetres to Feet and Inches:"
+ "\nEnter 2) Convert feet and inches to centimetres:");
Console.WriteLine(LengthCalculatorMenu);
} // End LengthCalculatorMenu
static int ValidLengthCalculatorReadOption() {
int LengthCalculatorOption;
bool ValidLengthCalculatorOption = false;
do {
LengthCalculatorOption = int.Parse(Console.ReadLine());
if ((LengthCalculatorOption >= 1) && (LengthCalculatorOption <= 2)) {
ValidLengthCalculatorOption = true;
} else {
ValidLengthCalculatorOption = false;
} // end if
if (!ValidLengthCalculatorOption) {
Console.WriteLine("\n\t Option must be 1 or 2, Please Re-Enter your Option");
LengthCalculatorMenu();
} //end if
} while (!ValidLengthCalculatorOption);
return LengthCalculatorOption;
}// End LengthCalculatorReadOption
static int ReadMainMenuOption() {
int option = 0;
bool ValidMainMenuOption = false;
do {
option = int.Parse(Console.ReadLine());
if ((option >= 1) && (option <= 5)) {
ValidMainMenuOption = true;
} else {
ValidMainMenuOption = false;
} // end if
if (option == 1) {
LengthCalculator();
} else if (option == 2) {
} else if (option == 3) {
} else if (option == 4) {
} else if (option == 5) {
} // end if
if (!ValidMainMenuOption) {
Console.WriteLine("\n\t\a Option must be 1,2,3,4 or 5");
DisplayMenu();
} //end if
} while (!ValidMainMenuOption);
return option;
} //end ReadOption
/* Displays Main Menu
* Precondition:true
* postcondition: DisplayMenu displayed
*/
static void DisplayMenu() {
string mainMenu = "\n1)Length Calculator"
+ "\n2)Body Mass Index Calculator"
+ "\n3)Waist to Height Calculator"
+ "\n4)Fuel Consumption Calculator"
+ "\n5)Exit the Calculator"
+ "\n\nEnter your option(1,2,3,4 or 5 to exit):";
Console.Write(mainMenu);
} //end DisplayMenu
static void Main(string[] args) {
const int Exit = 5;
int menuOption;
do {
DisplayMenu();
menuOption = ReadMainMenuOption();
} while (menuOption != Exit);
Console.Write("Thank you for using this Calculator. Press any Key to Exit");
//terminating message
Console.ReadKey();
}//end Main
You can make a separate method that will handle user input. For example, this method will determine if the user has entered a Y or N. If they haven't it re-prompt them to do so:
static bool AnotherConversion()
{
var prompt = "\nWould you like to make an another conversion? \n\n(Enter (Y) to make another conversion or (N) to return to the Main Menu):";
Console.WriteLine(prompt);
while (true)
{
var userInput = Console.ReadLine();
if (String.Compare("Y", userInput, StringComparison.Ordinal)
{
return true;
}
else if (String.Compare("N", userInput, StringComparison.Ordinal)
{
return false;
}
else
{
// Invlalid input, re-prompt
Console.WriteLine("Invalid Input, please enter or (Y) or (N)!");
Console.WriteLine(prompt);
}
}
}
You can them simply update your do/while loop so that the condition is based on the AnotherConversion method. This will allow the prompt to be asked whenever a calculation is done:
static int LengthCalculator() {
....
do {
.....
} while (AnotherConversion());
return LengthCalculatorOption;
}//End LenthCalculator
Call to this method in the place you want:
static bool shouldMakeAnotherConversion()
{
repeatQuestion:
// This shows the question to the user
Console.Write("Do you want to make another conversion (Y/N)? ");
ConsoleKeyInfo answer = Console.ReadKey(true);
switch (answer.Key)
{
case ConsoleKey.Y: return true;
case ConsoleKey.N: return false;
}
//If the user types any other key, the program will repeat the question
Console.WriteLine();
goto repeatQuestion;
}
class Program
{
public static void parameter(int num1, int num2, out int add, out int sub, out int mul, out float div)
{
add = num1 + num2;
sub = num1 - num2;
mul = num1 * num2;
div = (float)num1 / num2;
}
static void Main(string[] args)
{
int num1, num2;
int add, sub, mul;
float div;
Console.Write("Enter 1st number\t");
num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("\nEnter 2nd number\t");
num2 = Convert.ToInt32(Console.ReadLine());
Program.parameter(num1, num2, out add, out sub, out mul, out div);
Console.WriteLine("\n\n{0} + {1} = {2}", num1, num2, add);
Console.WriteLine("{0} - {1} = {2}", num1, num2, sub);
Console.WriteLine("{0} * {1} = {2}", num1, num2, mul);
Console.WriteLine("{0} / {1} = {2}", num1, num2, div);
Console.ReadLine();
}
}
}
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Type you first number :");
Console.WriteLine("Type you second number :");
Console.WriteLine("Enter the operation + (addition), - (soustraction), * (multiplication), / (division)");
string stringOperation = Console.ReadLine();
switch (operation)
{
case 1:
result = firstNumber + secondNumber;
break;
case 2:
result = firstNumber - secondNumber;
break;
case 3:
result = firstNumber * secondNumber;
break;
case 4:
result = firstNumber / secondNumber;
break;
}
}
}
}