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")
Related
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());
}
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
}
so I am trying to make a multiplication table with c#, and I want that when user give a wrong input in code it should not start the program from start but just ask to re-enter that value. when I run this code and put wrong input. it will ask to display the multiplication table again. but I want that if I give wrong input at "start value" then it will only ask for re-entering the start value but not the whole input
public void Multi()
{
Console.Write("\n\n");
bool tryAgain = true;
while (tryAgain)
{
try
{
Console.Write("Display the multiplication table:\n ");
int t = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("\n");
Console.WriteLine(" Start value ");
Console.WriteLine("\n");
Console.WriteLine(" End value \n");
int end = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\n");
SwapNum(ref start, ref end);
Console.Write("\n");
Console.WriteLine("Display the table\n");
int i = start;
do
{
Console.WriteLine(t + " * " + i + " = " + t * i);
//Console.WriteLine("{0} * {1} = {2}", t, i, t*i);
i++;
} while (i <= end);
}
catch (Exception ex)
{
Console.WriteLine("Please Enter the inter number ");
}
}
}
static void SwapNum(ref int x, ref int y)
{
if (x >= y)
{
int temp = x;
x = y;
y = temp;
}
}
Change Parse into TryParse; let's extract a method for this
private static int ReadInt(string prompt) {
while (true) {
Console.WriteLine(prompt);
int result;
if (int.TryParse(Console.ReadLine(), out result))
return result;
Console.WriteLine("Sorry, it's not a correct integer value, please try again.");
}
}
...
public void Multi() {
Console.Write("Display the multiplication table:\n ");
// Now we keep asking user until the correct value entered
int t = ReadInt("Start value");
...
}
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);
....
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConTempConversion_LeeMichelle
{
class Program
{
static void Main(string[] args)
{
double fTemp;
double cTemp;
double convertC;
double convertF;
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("_________________________________________________");
Console.WriteLine("1. Fahrenheit to Celsius");
Console.WriteLine("2. Celsius to Fahrenheit");
Console.WriteLine("3. Exit");
Console.Write("Enter choice: ");
Console.ReadKey();
int ichoice = 0;
do
{
if (ichoice == 1)
{
Console.WriteLine("Enter Fahrenheit temperature: ");
fTemp = int.Parse(Console.ReadLine());
convertC = ConvertCelcius(fTemp);
Console.WriteLine(fTemp + "Fahrenheit is " + convertC + "Celsius");
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("_________________________________________________");
Console.ReadKey();
}
if (ichoice == 2)
{
Console.WriteLine("Enter Celsius temperature: ");
cTemp = int.Parse(Console.ReadLine());
convertF = ConvertFahrenheit(cTemp);
Console.WriteLine(cTemp + "Celsius is " + convertF + "Fahrenheit");
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("____________________________________________________");
Console.ReadKey();
}
if (ichoice == 3)
{
Console.WriteLine("Thank you for using the temperature conversion application. Please come again.");
}
else
{
Console.WriteLine("Invalid choice. Please choose again!");
}
}
while (ichoice > 3);
Console.ReadKey();
}
static double ConvertCelcius(double c){
double f;
return f= 9.0 / 5.0 * c + 32;
}
static double ConvertFahrenheit(double f) {
double c;
return c = 5.0 / 9.0 * (f - 32);
}
}
}
so suppose the user has three options from 1 - 3. After option 3, there will be an error alert. my problem is why this code gives me an infinity loop? what did I do wrong? can I put break after each if statment?
Please help, thank you!
You're creating a do...while loop without anything to ever exit it. When the loop begins, ichoice is already set in stone. So you'll always be stuck in that loop!
You are never assigning a value to ichoice If I were you, I would try something like this:
int ichoice = 0;
int.TryParse(Console.ReadKey().ToString(), out ichoice );
do
{
if (ichoice == 1)
{
Console.WriteLine("Enter Fahrenheit temperature: ");
fTemp = int.Parse(Console.ReadLine());
convertC = ConvertCelcius(fTemp);
Console.WriteLine(fTemp + "Fahrenheit is " + convertC + "Celsius");
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("_________________________________________________");
int.TryParse(Console.ReadKey().ToString(), out ichoice );
Add the int.TryParse(Console.ReadKey().ToString(), out ichoice ); everywhere you have Console.Readline(). What this is doing is getting the user input and converting it to an integer (if it's not an integer, then the value is 0).
Also add this:
if (ichoice == 3)
{
Console.WriteLine("Thank you for using the temperature conversion application. Please come again.");
break;
}
else
{
Console.WriteLine("Invalid choice. Please choose again!");
int.TryParse(Console.ReadKey().ToString(), out ichoice );
}
Finally, remove this (I'm not quite sure what it was for...)
while (ichoice > 3);
Console.ReadKey();
When you need to do some prep work before your condition, the most straightforward way involves combining your loop with a separate structure.
This is the format to use when your loop condition is at the beginning of the loop:
prep work
while (condition) // if false then loop body will never run
{
loop body
}
This is the format to use when the loop condition is at the end of the loop:
prep work
do
{
loop body
}
while (condition); // loop body will always execute at least once
In this case, you have some prep work to do before each iteration--you want to get the key press from the user each time. For this, I recommend the following from Code Complete:
while (true) // loop termination condition is inside the loop
{
prep work
if (condition)
{
break;
}
loop body
}
In your case, it would look something like:
Console.Write("Enter choice: ");
while (true) // loop termination condition is inside the loop
{
Console.ReadKey();
if (ichoice == 3)
{
Console.WriteLine(...);
break;
}
...
}
Also, consider changing most of your ifs into else ifs; otherwise, you're repeatedly checking the condition even when you've gone through one case.
you should assign a value to iChoice. and set your while to read a terminating character. like:
namespace YourNameSpace
{
static void Main(string[] args)
{
double fTemp;
double cTemp;
double convertC;
double convertF;
int iChoice;
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("_________________________________________________");
Console.WriteLine("1. Fahrenheit to Celsius");
Console.WriteLine("2. Celsius to Fahrenheit");
Console.Write("Enter choice(0 to exit): ");
iChoice = Console.Read();
do{
switch(iChoice)
{
case 1:
Console.WriteLine("Enter Fahrenheit temperature: ");
fTemp = int.Parse(Console.ReadLine());
convertC = ConvertCelcius(fTemp);
Console.WriteLine(fTemp + "Fahrenheit is " + convertC + "Celsius");
case 2:
Console.WriteLine("Enter Celsius temperature: ");
cTemp = int.Parse(Console.ReadLine());
convertF = ConvertFahrenheit(cTemp);
Console.WriteLine(cTemp + "Celsius is " + convertF + "Fahrenheit");
}
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("_________________________________________________");
Console.WriteLine("1. Fahrenheit to Celsius");
Console.WriteLine("2. Celsius to Fahrenheit");
Console.Write("Enter choice(0 to exit): ");
iChoice = Console.Read();
}while(iChoice != 0);
}
static double ConvertCelcius(double c){
double f;
return f= 9.0 / 5.0 * c + 32;
}
static double ConvertFahrenheit(double f) {
double c;
return c = 5.0 / 9.0 * (f - 32);
}
}
Each time you call Console.ReadKey you should store returning value.You are receiving input from user but you didn't store it anywhere.
First you can create a function to get ichoice, and force user to enter the correct value:
static void GetChoice(ref int ichoice)
{
string input = Console.ReadLine();
Console.Write("Enter choice: ");
bool result = int.TryParse(input, out ichoice);
if (!result)
{
while (!result && ichoice > 3)
{
Console.WriteLine("Invalid value.Try again:");
input = Console.ReadLine();
result = int.TryParse(input, out ichoice);
}
}
}
Then use this function whenever you need to make a choice.
Here is the working version or your program:
double fTemp;
double cTemp;
double convertC;
double convertF;
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("_________________________________________________");
Console.WriteLine("1. Fahrenheit to Celsius");
Console.WriteLine("2. Celsius to Fahrenheit");
Console.WriteLine("3. Exit");
int ichoice = 0;
GetChoice(ref ichoice);
do
{
if (ichoice == 1)
{
Console.WriteLine("Enter Fahrenheit temperature: ");
fTemp = int.Parse(Console.ReadLine());
convertC = ConvertCelcius(fTemp);
Console.WriteLine(fTemp + "Fahrenheit is " + convertC + "Celsius");
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("_________________________________________________");
GetChoice(ref ichoice);
}
if (ichoice == 2)
{
Console.WriteLine("Enter Celsius temperature: ");
cTemp = int.Parse(Console.ReadLine());
Console.WriteLine(cTemp + "Celsius is " + cTemp + "Fahrenheit");
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("____________________________________________________");
GetChoice(ref ichoice);
}
if (ichoice == 3)
{
Console.WriteLine("Thank you for using the temperature conversion application. Please come again.");
}
else
{
Console.WriteLine("Invalid choice. Please choose again!");
}
}
while (ichoice < 3);
}
static double ConvertCelcius(double c)
{
double f;
return f = 9.0 / 5.0 * c + 32;
}
static double ConvertFahrenheit(double f)
{
double c;
return c = 5.0 / 9.0 * (f - 32);
}
And here is the full code: http://pastebin.com/bkegSAFL