Trying to make a calculator - c#

so basically whenever i try to change the variable "restart" inside of the while loop it gives me an error saying "a local or parameter named 'restart' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter". if anyone knows how to fix this please tell me
public class Program
{
public static void Main()
{
bool restart = true;
while (restart == true)
{
Console.WriteLine("please enter Multiply, Divide, Add Or Subtract");
string Method = Console.ReadLine();
if (Method == "Add")
{
Console.WriteLine("Please Enter First Number");
double numberOne = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Please Enter The Second Number");
double numberTwo = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(numberOne + numberTwo);
Console.WriteLine("Would You Like To Use The Calculator Again? (true = yes, false = no)");
bool restart = Convert.ToBoolean(Console.ReadLine());
}
else if (Method == "Subtract")
{
Console.WriteLine("Please Enter First Number");
double numberOne = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Please Enter The Second Number");
double numberTwo = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(numberOne - numberTwo);
Console.WriteLine("Would You Like To Use The Calculator Again? (true = yes, false = no)");
bool restart = Convert.ToBoolean(Console.ReadLine());
}
else if (Method == "Multiply")
{
Console.WriteLine("Please Enter First Number");
double numberOne = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Please Enter The Second Number");
double numberTwo = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(numberOne * numberTwo);
Console.WriteLine("Would You Like To Use The Calculator Again? (true = yes, false = no)");
bool restart = Convert.ToBoolean(Console.ReadLine());
}
else if (Method == "Divide")
{
Console.WriteLine("Please Enter First Number");
double numberOne = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Please Enter The Second Number");
double numberTwo = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(numberOne / numberTwo);
Console.WriteLine("Would You Like To Use The Calculator Again? (true = yes, false = no)");
bool restart = Convert.ToBoolean(Console.ReadLine());
}
else
{
Console.WriteLine("error found");
Console.WriteLine("Would You Like To Use The Calculator Again? (true = yes, false = no)");
bool restart = Convert.ToBoolean(Console.ReadLine());
}
}
}
}```

Let's look at this part of your code:
bool restart = true;
while (restart == true)
{
// Some stuff omitted...
bool restart = Convert.ToBoolean(Console.ReadLine());
}
You redeclare restart. Instead, you should just assign it like this (leave bool off when you use the variable after first declaring it):
restart = Convert.ToBoolean(Console.ReadLine());

You need something like this:
bool restart = true;
while (restart)
{
Console.WriteLine("please enter Multiply, Divide, Add Or Subtract");
string method = Console.ReadLine();
if (new[] { "Multiply", "Divide", "Add", "Subtract" }.Contains(method))
{
Console.WriteLine("Please Enter First Number");
double numberOne = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Please Enter The Second Number");
double numberTwo = Convert.ToDouble(Console.ReadLine());
if (method == "Add")
{
Console.WriteLine(numberOne + numberTwo);
}
else if (method == "Subtract")
{
Console.WriteLine(numberOne - numberTwo);
}
else if (method == "Multiply")
{
Console.WriteLine(numberOne * numberTwo);
}
else if (method == "Divide")
{
Console.WriteLine(numberOne / numberTwo);
}
Console.WriteLine("Would You Like To Use The Calculator Again? (true = yes, false = no)");
restart = Convert.ToBoolean(Console.ReadLine());
}
else
{
Console.WriteLine("error found");
Console.WriteLine("Would You Like To Use The Calculator Again? (true = yes, false = no)");
restart = Convert.ToBoolean(Console.ReadLine());
}
}
Or this:
Dictionary<string, Func<double, double, double>> operations =
new Dictionary<string, Func<double, double, double>>()
{
{ "Add", (x, y) => x + y },
{ "Subtract", (x, y) => x - y },
{ "Multiply", (x, y) => x * y },
{ "Divide", (x, y) => x / y },
};
bool restart = true;
while (restart)
{
Console.WriteLine($"Please enter one of: {String.Join(", ", operations.Keys)}");
string method = Console.ReadLine();
if (operations.ContainsKey(method))
{
Console.WriteLine("Please Enter First Number");
double numberOne = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Please Enter The Second Number");
double numberTwo = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(operations[method](numberOne, numberTwo));
}
else
{
Console.WriteLine("error found");
}
Console.WriteLine("Would You Like To Use The Calculator Again? (true = yes, false = no)");
restart = Convert.ToBoolean(Console.ReadLine());
}

Related

I can't figure out why my Console.ReadLine() is not working

I'm relatively new to programming and I'm working on various projects to get better at it. One is a calculator that I want to be able to solve more than just basic addition and subtraction. Currently, all I have is the basics with the quadratic formula. But my design weighs on user input to decide what to do. It prompts the user with "What would you like to do? Add: Sub: Div: Mul: Quad Equation:" After typic in "Add" the code operates normally but if I type in anything else like "Sub" or "Div". it does nothing. doesn't even spit back an error. As far as I can tell, my code is fine (well it's terrible code but it should work nonetheless) But I just do not know how to proceed.
using System;
namespace Better_Calculator
{
class Program
{
static void Main(string[] args)
{
double num01;
double num02;
double a;
double b;
double c;
System.Console.WriteLine("Welcome to how you are going to cheat through math lol");
System.Console.WriteLine("What would you like to do? \nAdd: \nSub: \nDiv: \nMul: \nQuad Equation: ");
if (Console.ReadLine() == "Add")
{
System.Console.WriteLine("what is the first number?");
num01 = Convert.ToInt32(Console.ReadLine());
System.Console.WriteLine("what is the second number?");
num02 = Convert.ToInt32(Console.ReadLine());
Add(num01, num02);
}
else if (System.Console.ReadLine() == "Sub")
{
System.Console.WriteLine("what is the first number?");
num01 = Convert.ToInt32(Console.ReadLine());
System.Console.WriteLine("what is the second number?");
num02 = Convert.ToInt32(Console.ReadLine());
Sub(num01, num02);
}
else if (System.Console.ReadLine() == "Mul")
{
System.Console.WriteLine("what is the first number?");
num01 = Convert.ToInt32(Console.ReadLine());
System.Console.WriteLine("what is the second number?");
num02 = Convert.ToInt32(Console.ReadLine());
Mul(num01, num02);
}
else if (System.Console.ReadLine() == "Div")
{
System.Console.WriteLine("what is the first number?");
num01 = Convert.ToInt32(Console.ReadLine());
System.Console.WriteLine("what is the second number?");
num02 = Convert.ToInt32(Console.ReadLine());
Div(num01, num02);
}
else if (System.Console.ReadLine() == "Quad Equation")
{
System.Console.WriteLine("what is a?");
a = Convert.ToInt32(Console.ReadLine());
System.Console.WriteLine("what is b");
b = Convert.ToInt32(Console.ReadLine());
System.Console.WriteLine("what is c");
c = Convert.ToInt32(Console.ReadLine());
Quad(a, b, c);
}
static void Add(double num01, double num02)
{
string answer = Convert.ToString(num01 + num02);
System.Console.WriteLine(answer);
}
static void Sub(double num01, double num02)
{
string answer = Convert.ToString(num01 - num02);
System.Console.WriteLine(answer);
}
static void Mul(double num01, double num02)
{
string answer = Convert.ToString(num01 * num02);
System.Console.WriteLine(answer);
}
static void Div(double num01, double num02)
{
string answer = Convert.ToString(num01 / num02);
System.Console.WriteLine(answer);
}
static void Quad(double a, double b, double c)
{
double bNeg = b * -1;
double bSqr = b * b;
double SqR = Math.Sqrt(bSqr - (4 * a * c));
double solvedAdd = (bNeg + SqR) / (2 * a);
double solvedSub = (bNeg - SqR) / (2 * a);
string answer = Convert.ToString(solvedAdd) + " or " + Convert.ToString(solvedSub);
System.Console.WriteLine(answer);
}
}
}
}
With every ´if´, you call Console.ReadLine() again, so if you enter "Quad Equation", your code has passed 5 Readlines until you reach the code that does Quad Equation.
Solution: Do only one Console.ReadLine() and put its result into a variable:
var userInput = Console.ReadLine();
and then, test against userInput in your if statements (ex.)e:
else if (userInput == "Sub")
You only need to do a ReadLine once and store the value, then use that to compare. For example:
var operation = Console.ReadLine();
if(operation == "Add")
{
// Do add stuff
}
But you should consider using a switch statement instead:
switch(operation)
{
case "Add":
// do Add Stuff
break;
case "Sub":
// do Add Stuff
break;
case "Mul":
// do Add Stuff
break;
// etc...
}
When we get input from console application from user may be they given as
CAPS, Small or combination of both
. In that situation you can use the following approach,
string value=Console.ReadLine();
if(string.Equals(value, "Add", StringComparison.CurrentCultureIgnoreCase))
{
// Do add stuff
}
else if(string.Equals(value, "Sub", StringComparison.CurrentCultureIgnoreCase))
{
// Do add stuff
}

How can I make my C# calculator run as intended

I have a C# calculator I'm trying to get to run however I keep running into problems, particularly with my last function and currently get stuck in an infinite validation loop, how can I make this work as intended which is to take two numbers and based on user input get the answer for their equation.
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello User what is your name?");
string name = Console.ReadLine();
Console.WriteLine("Hello " + name + " Please enter in a number");
Console.ReadLine();
Console.WriteLine("Please enter a Math Operator: +, -, *, / ");
string beta = IsValidSymbol();
string equation = Console.ReadLine();
string useint1 = Console.ReadLine();
string useint2 = Console.ReadLine();
Console.WriteLine("Please enter another number");
Console.WriteLine(MathSymbols(equation,useint1,useint2));
}
public static double Validation()
{
string numbString = Console.ReadLine();
double numbVerify;
while (!double.TryParse(numbString, out numbVerify))
{
Console.WriteLine("please only enter in numbers and do not leave blank");
numbString = Console.ReadLine();
}
return numbVerify;
}
private static string IsValidSymbol()
{
string mathValidation = Console.ReadLine();
while ((String.IsNullOrEmpty(mathValidation)))
{
Console.WriteLine("Please, do not leave the sentence field empty!");
Console.WriteLine("Enter a Math Operator: +, -, *, / ");
mathValidation = Console.ReadLine();
}
return mathValidation;
}
private static double MathSymbols(string e, string useint1,string useint2)
{
useint1 = Console.ReadLine();
useint2 = Console.ReadLine();
double result;
double userinput1;
double userinput2;
while (!double.TryParse(useint1, out userinput1))
{
Console.WriteLine("please type in a number");
useint1 = Console.ReadLine();
}
while (!double.TryParse(useint2, out userinput2))
{
Console.WriteLine("please type in a number");
useint1 = Console.ReadLine();
}
if (e == "+")
{
result = userinput1 + userinput2;
}
else if (e == "-")
{
result = userinput1 - userinput2;
}
else if (e == "*")
{
result = (userinput1 * userinput2);
}
else if (e == "/")
{
result = (userinput1 / userinput2);
}
result = 0;
return result;
}
}
}
In many places you had an unnecessary call to Console.ReadLine and overriding variables. Also you didn't use your method Validation (think about renaming it to GetValidNumber).
I corrected your code to work for valid input. You still need additional validations and refactoring in your code, good luck!
using System;
namespace CalculatorExample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello User what is your name?");
string name = Console.ReadLine();
Console.WriteLine("Hello " + name + " Please enter in a number");
double useint1 = Validation();
Console.WriteLine("Please enter a Math Operator: +, -, *, / ");
string equation = IsValidSymbol();
Console.WriteLine($"You equation symbol: {equation}");
Console.WriteLine("Please enter another number");
double useint2 = Validation();
double result = MathSymbols(equation, useint1, useint2);
Console.WriteLine($"Result: {result}");
Console.ReadKey();
}
public static double Validation()
{
string numbString = Console.ReadLine();
double numbVerify;
while (!double.TryParse(numbString, out numbVerify))
{
Console.WriteLine("please only enter in numbers and do not leave blank");
numbString = Console.ReadLine();
}
return numbVerify;
}
private static string IsValidSymbol()
{
string mathValidation = Console.ReadLine();
while ((String.IsNullOrEmpty(mathValidation)))
{
Console.WriteLine("Please, do not leave the sentence field empty!");
Console.WriteLine("Enter a Math Operator: +, -, *, / ");
mathValidation = Console.ReadLine();
}
return mathValidation;
}
private static double MathSymbols(string equation, double useint1, double useint2)
{
if (equation == "+")
return useint1 + useint2;
if (equation == "-")
return useint1 - useint2;
if (equation == "*")
return useint1 * useint2;
if (equation == "/")
return useint1 / useint2;
throw new InvalidOperationException($"Unrecognized equation symbol: {equation}");
}
}
}

Simple console application calculator functions

I've tested a simple calculator functions as a part of my C# studies and I have a problem, it won't exit the while loop even if I type the right choise.
Here is the code:
static void Main(string[] args)
{
string calc, inputX, inputY, inputZ;
double x, y, z;
Console.Write("Welcome to the cool calculator. Please choose between sumCalc or multiCalc: ");
calc = Console.ReadLine();
while (calc != "sumCalc" || calc != "sumCalc")
{
Console.Write("Please type in the right calculator again: ");
calc = Console.ReadLine();
}
if (calc == "sumCalc")
{
Console.WriteLine("You are now working with the sumCalc.");
//Getting user input for the variable 'x'
Console.WriteLine("Please enter a value for the first number:");
inputX = Console.ReadLine();
x = Convert.ToDouble(inputX);
//Getting user input for the variable 'y'
Console.WriteLine("Please enter a value for the second number:");
inputY = Console.ReadLine();
y = Convert.ToDouble(inputY);
//Getting user input for the variable 'z'
Console.WriteLine("Please enter a value for the third number:");
inputZ = Console.ReadLine();
z = Convert.ToDouble(inputZ);
Console.WriteLine("The result is:" + sumCalc(x, y, z));
Console.ReadKey();
}
else if (calc == "multiCalc")
{
Console.WriteLine("You are now working with the multiCalc.");
//Getting user input for the variable 'x'
Console.WriteLine("Please enter a value for the first number:");
inputX = Console.ReadLine();
x = Convert.ToDouble(inputX);
//Getting user input for the variable 'y'
Console.WriteLine("Please enter a value for the second number:");
inputY = Console.ReadLine();
y = Convert.ToDouble(inputY);
//Getting user input for the variable 'z'
Console.WriteLine("Please enter a value for the third number:");
inputZ = Console.ReadLine();
z = Convert.ToDouble(inputZ);
Console.WriteLine("The result is:" + multiCalc(x, y, z));
Console.ReadKey();
}
}
//This is the multiply calculator function
static double sumCalc(double x, double y, double z)
{
double res = x + y + z;
return res;
}
//This is the multiply calculator function
static double multiCalc(double x, double y, double z)
{
double res = x * y * z;
return res;
}
I don't know why it does that, it should work just fine.
Please help me, thanks! :)
You have sumCalc twice in while condition. Also change || to &&, if you use OR as the condition, even if you enter sumCalc OR multiCalc, the loop will be true and keep asking you to enter again.
while (calc != "sumCalc" && calc != "multiCalc")
Try to change your code :
while (calc != "sumCalc" && calc != "multiCalc")
instead of :
while (calc != "sumCalc" || calc != "sumCalc")

C# the variable UserInput cannot find the definition

double UserInput;
string y, z;
double OunceToGram, PoundToOunce, PoundToKilogram, PintToLitre, InchToCenti, MilesToInch;
OunceToGram = UserInput * 28.0; //(error is here, it cannot find UserInput)
PoundToOunce = UserInput * 16.0;
PoundToKilogram = UserInput * 0.454;
PintToLitre = UserInput * 0.568;
InchToCenti = UserInput * 2.5;
MilesToInch = UserInput * 63360.0;
int i = 0;
while (i < UserInput)
{
Console.WriteLine("");
Console.WriteLine("Please enter a unit to convert, type a num <1 to cancel");
UserInput = Convert.ToDouble(Console.ReadLine());
You could resolve your problem not converting immediately the user input to your variable UserInput and checking if the user types a conventional letter to stop the input
double UserInput = 0.0; // <- You need to initialize before using it ...
.....
string stopInput = "N";
while (stopInput != "Q"))
{
Console.WriteLine("");
Console.WriteLine("Please enter a unit to convert, type 'Q' to cancel");
stopInput = Console.ReadLine();
if(stopInput == "Q")
break;
UserInput = Convert.ToDouble(stopInput);
....
}

No overload method 'conversationOutput' takes '2' arguments

Hi I'm having trouble with an error "No overload method 'conversationOutput' takes '2' arguments" please help. I'm having a little trouble understanding method calling, and calling variables from main().
class MainClass
{
static void Main ()
{
string selection;
double values;
selection = userChoice();
values = userInput(selection);
conversationOutput(selection, values);
}
static string userChoice ()
{
string choose;
Console.WriteLine("Welcome to the OHM's law calculator! \n \nWhat would you like to calcualte?");
Console.WriteLine("1. Voltage:");
Console.WriteLine("2. Current:");
Console.WriteLine("3. Resistance:");
do
{
choose = Console.ReadLine();
if (choose != "1" && choose != "2" && choose != "3")
{
Console.WriteLine("Please only select '1' for voltage, '2' for current, '3' resistance");
}
} while (choose != "1" && choose != "2" && choose != "3");
switch (choose)
{
case "1":
Console.Write("You have choose to calculate Voltage.\n");
break;
case "2":
Console.Write("You have choose to calculate Current.\n");
break;
case "3":
Console.WriteLine("You have choose to calculate Resistance.\n");
break;
}
return choose;
}
static double userInput (string choose)
{
double voltageD = 0.0;
double currentD = 0.0;
double resistanceD = 0.0;
string current;
string voltage;
string resistance;
bool ok = true;
do if (choose != "1")
{
do
{
Console.WriteLine("Please enter your value for Voltage (volts)...");
voltage = Console.ReadLine();
ok = double.TryParse(voltage, out voltageD);
if (!ok)
{
Console.WriteLine("Please Enter a NUMERICALE VALUE ONLY");
}
} while (!ok);
if (voltageD < 0)
{
Console.WriteLine("Please select a number larger than the lower limit of 0 volts");
}
} while (voltageD < 0);
do if (choose != "2")
{
do
{
Console.WriteLine("Please enter your value for Current (amp)...");
current = Console.ReadLine();
ok = double.TryParse(current, out currentD);
if (!ok)
{
Console.WriteLine("Please Enter a NUMERICALE VALUE ONLY");
}
} while (!ok);
if (currentD < 0.01)
{
Console.WriteLine("Please select a number larger than the lower limit of 0.01 amp");
}
} while (currentD < 0.01);
do if (choose != "3")
{
do
{
Console.WriteLine("Please enter your value for Resistance (ohm)...");
resistance = Console.ReadLine();
ok = double.TryParse(resistance, out resistanceD);
if (!ok)
{
Console.WriteLine("Please Enter a NUMERICALE VALUE ONLY");
}
} while (!ok);
if (resistanceD < 10)
{
Console.WriteLine("Please select a number larger than the lower limit of 10 ohm");
}
} while (resistanceD < 10);
return 0;
}
static double conversationOutput (string choose, double currentD, double voltageD, double resistanceD)
{
/* v = i*r */
double output = 0.0;
string units = "";
if (choose == "1")
{
output = (currentD) * (resistanceD);
units = "Volts";
}
if (choose == "2")
{
output = (voltageD) / (resistanceD);
units = "Amps";
}
if (choose == "3")
{
output = (voltageD) / (resistanceD);
units = "OHM";
}
Console.WriteLine("The calculated value is {0:F3} {1:F3}", output, units);
return 0;
}
}
The reason is you have a method
double conversationOutput (string choose, double currentD, double voltageD, double resistanceD)
which has 4 parameters and you are passing only 2 parameters to the method.
define the missing parameters as optional
static double conversationOutput (string choose, double currentD, double voltageD =0, double resistanceD =1)
As per the method definition, conversationOutput expects four parameters.
static double conversationOutput (string choose, double currentD, double voltageD, double resistanceD) {}
But you are calling it by passing just two parameters.
conversationOutput(selection, values);
That's why you are getting such error.
It will work if you call the conversationOutput method by passing four parameters.

Categories