How do I keep the previous equations from being displayed - c#

I have a project where the user can insert a math equation in a single line using the split command. In the first loop the equation get solved correctly and displays the equation with the answer. The problem is with the second loop. It solves the equation and displays the equation with the answer but it also displays the equation from before.
using System;
namespace Calculator1
{
class Program
{
static void Main(string[] args)
{
double answer;
double answer1;
bool Continue = true;
Console.WriteLine("\tCalculator");
Console.WriteLine("--------------------------\n");
Console.WriteLine(" Math Operations: ");
Console.WriteLine(" --------------------");
Console.WriteLine(" Multiplication: *");
Console.WriteLine(" Addition: +");
Console.WriteLine(" Subtraction: -");
Console.WriteLine(" Division: /");
Console.WriteLine("\nEnter your equation below:");
Console.WriteLine("For example: 5 + 5 ");
string[] values = Console.ReadLine().Split(' ');
double firstNum = double.Parse(values[0]);
string operation = (values[1]);
double secondNum = double.Parse(values[2]);
while (Continue)
{
if (operation == "*")
{
answer = firstNum * secondNum;
Console.WriteLine("\n" + firstNum + " * " + secondNum + " = " + answer);
}
else if (operation == "/")
{
answer = firstNum / secondNum;
Console.WriteLine("\n" + firstNum + " / " + secondNum + " = " + answer);
}
else if (operation == "+")
{
answer = firstNum + secondNum;
Console.WriteLine("\n" + firstNum + " + " + secondNum + " = " + answer);
}
else if (operation == "-")
{
answer = firstNum - secondNum;
Console.WriteLine("\n" + firstNum + " - " + secondNum + " = " + answer);
}
else
{
Console.WriteLine("Sorry that is not correct format! Please restart!");
}
Console.WriteLine("\n\nDo you want to continue?");
Console.WriteLine("Type in Yes or No:");
string response = Console.ReadLine();
if (response == "Yes")
{
Console.WriteLine("\nEnter your equation below:");
string[] values1 = Console.ReadLine().Split(' ');
double firstNum1 = double.Parse(values1[0]);
string operation1 = (values1[1]);
double secondNum1 = double.Parse(values1[2]);
if (operation1 == "*")
{
answer1 = firstNum1 * secondNum1;
Console.WriteLine("\n" + firstNum1 + " * " + secondNum1 + " = " + answer1);
}
else if (operation1 == "/")
{
answer1 = firstNum1 / secondNum1;
Console.WriteLine("\n" + firstNum1 + " / " + secondNum1 + " = " + answer1);
}
else if (operation1 == "+")
{
answer1 = firstNum1 + secondNum1;
Console.WriteLine("\n" + firstNum1 + " + " + secondNum1 + " = " + answer1);
}
else if (operation1 == "-")
{
answer1 = firstNum1 - secondNum1;
Console.WriteLine("\n" + firstNum1 + " - " + secondNum1 + " = " + answer1);
}
else
{
Console.WriteLine("Sorry that is not correct format! Please restart!");
}
}
else
{
Continue = false;
}
}
}
}
}
Output:
Math Operations:
--------------------
Multiplication: *
Addition: +
Subtraction: -
Division: /
Enter your equation below:
For example: 5 + 5
5 + 5
5 + 5 = 10
Do you want to continue?
Type in Yes or No:
Yes
Enter your equation below:
10 + 10
10 + 10 = 20
5 + 5 = 10 \\ I don't want this to appear
Do you want to continue?
Type in Yes or No:

All you need to do is put the code that gets the user input into the while loop, and then let the loop continue if the user answers "Yes" at the end of the loop:
private static void Main()
{
double answer;
double answer1;
bool Continue = true;
Console.WriteLine("\tCalculator");
Console.WriteLine("--------------------------\n");
Console.WriteLine(" Math Operations: ");
Console.WriteLine(" --------------------");
Console.WriteLine(" Multiplication: *");
Console.WriteLine(" Addition: +");
Console.WriteLine(" Subtraction: -");
Console.WriteLine(" Division: /");
while (Continue)
{
Console.WriteLine("\nEnter your equation below:");
Console.WriteLine("For example: 5 + 5 ");
string[] values = Console.ReadLine().Split(' ');
double firstNum = double.Parse(values[0]);
string operation = (values[1]);
double secondNum = double.Parse(values[2]);
if (operation == "*")
{
answer = firstNum * secondNum;
Console.WriteLine("\n" + firstNum + " * " + secondNum + " = " + answer);
}
else if (operation == "/")
{
answer = firstNum / secondNum;
Console.WriteLine("\n" + firstNum + " / " + secondNum + " = " + answer);
}
else if (operation == "+")
{
answer = firstNum + secondNum;
Console.WriteLine("\n" + firstNum + " + " + secondNum + " = " + answer);
}
else if (operation == "-")
{
answer = firstNum - secondNum;
Console.WriteLine("\n" + firstNum + " - " + secondNum + " = " + answer);
}
else
{
Console.WriteLine("Sorry that is not correct format! Please restart!");
}
Console.WriteLine("\n\nDo you want to continue?");
Console.WriteLine("Type in Yes or No:");
string response = Console.ReadLine();
if (response != "Yes") Continue = false;
}
}

Your Issue:
Its because you have the output code twice in the loop and both of them are displaying different variables.
Solution:
namespace Calculator1
{
class Program
{
static void Main(string[] args)
{
double answer;
double answer1;
bool Continue = true;
Console.WriteLine("\tCalculator");
Console.WriteLine("--------------------------\n");
Console.WriteLine(" Math Operations: ");
Console.WriteLine(" --------------------");
Console.WriteLine(" Multiplication: *");
Console.WriteLine(" Addition: +");
Console.WriteLine(" Subtraction: -");
Console.WriteLine(" Division: /");
while (Continue)
{
Console.WriteLine("\nEnter your equation below:");
Console.WriteLine("For example: 5 + 5 ");
string[] values = Console.ReadLine().Split(' ');
double firstNum = double.Parse(values[0]);
string operation = (values[1]);
double secondNum = double.Parse(values[2]);
if (operation == "*")
{
answer = firstNum * secondNum;
Console.WriteLine("\n" + firstNum + " * " + secondNum + " = " + answer);
} else if (operation == "/")
{
answer = firstNum / secondNum;
Console.WriteLine("\n" + firstNum + " / " + secondNum + " = " + answer);
} else if (operation == "+")
{
answer = firstNum + secondNum;
Console.WriteLine("\n" + firstNum + " + " + secondNum + " = " + answer);
} else if (operation == "-")
{
answer = firstNum - secondNum;
Console.WriteLine("\n" + firstNum + " - " + secondNum + " = " + answer);
} else
{
Console.WriteLine("Sorry that is not correct format! Please restart!");
}
Console.WriteLine("\n\nDo you want to continue?");
Console.WriteLine("Type in Yes or No:");
string response = Console.ReadLine();
Continue = (response == "Yes");
}
}
}
}

Related

How do I use variable created in a scope outside of it or at least a way around this [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 months ago.
Improve this question
I have been working on this one assignment for two weeks now and I can't figure it out. I have seen some things on here that mention using classes and methods but in the assignment instructions it says not to use them since we haven't learned it yet.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
namespace Assignment_2
{
class Program
{
static void Main(string[] args)
{
Write("Enter a salesperson's name: ");
string name = ReadLine();
do
{
Write("\n" + "Enter an item number between 1 and 4 or -1 to quit: ");
String item = ReadLine();
int intItem = Convert.ToInt32(item);
Write("\n" + "Enter the quantity sold: ");
String quantity = ReadLine();
int intQuantity = Convert.ToInt32(quantity);
switch (intItem)
{
case 1:
{
Double price = 239.99;
double total = price * intQuantity;
WriteLine("Salesperson " + name + " sold " + intQuantity + " of item #" + intItem + " at $" + total);
double dblTotalSales = +total;
break;
}
case 2:
{
Double price = 129.75;
double total = price * intQuantity;
WriteLine("Salesperson " + name + " sold " + intQuantity + " of item #" + intItem + " at $" + total);
double dblTotalSales = +total;
break;
}
case 3:
{
Double price = 99.95;
double total = price * intQuantity;
WriteLine("Salesperson " + name + " sold " + intQuantity + " of item #" + intItem + " at $" + total);
double dblTotalSales = +total;
break;
}
case 4:
{
Double price = 350.89;
double total = price * intQuantity;
WriteLine("Salesperson " + name + " sold " + intQuantity + " of item #" + intItem + " at $" + total);
double dblTotalSales = +total;
break;
}
case -1:
{
WriteLine("Salesperson " + name + " sold a total of $" + dblTotalSales);
break;
}
}
} while (true);
}
}
}
Your problem is the variable dblTotalSales.
You are declaring the variable as a new variable inside each case of your switch statement, which means it is scoped to ONLY the specific case where it is declared.
If you are wanting to make the variable accessible to all of the case's, the variable needs to be declared outside the scope of the switch statement:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
namespace Assignment_2
{
class Program
{
static void Main(string[] args)
{
Write("Enter a salesperson's name: ");
string name = ReadLine();
// declare here to be outside the scope of the loop,
// but accessible to everything inside the loop.
double dblTotalSales = 0;
do
{
Write("\n" + "Enter an item number between 1 and 4 or -1 to quit: ");
String item = ReadLine();
int intItem = Convert.ToInt32(item);
Write("\n" + "Enter the quantity sold: ");
String quantity = ReadLine();
int intQuantity = Convert.ToInt32(quantity);
switch (intItem)
{
case 1:
{
Double price = 239.99;
double total = price * intQuantity;
WriteLine("Salesperson " + name + " sold " + intQuantity + " of item #" + intItem + " at $" + total);
// now just reference the previously declared variable
dblTotalSales = +total;
break;
}
case 2:
{
Double price = 129.75;
double total = price * intQuantity;
WriteLine("Salesperson " + name + " sold " + intQuantity + " of item #" + intItem + " at $" + total);
// now just reference the previously declared variable
dblTotalSales = +total;
break;
}
case 3:
{
Double price = 99.95;
double total = price * intQuantity;
WriteLine("Salesperson " + name + " sold " + intQuantity + " of item #" + intItem + " at $" + total);
// now just reference the previously declared variable
dblTotalSales = +total;
break;
}
case 4:
{
Double price = 350.89;
double total = price * intQuantity;
WriteLine("Salesperson " + name + " sold " + intQuantity + " of item #" + intItem + " at $" + total);
// now just reference the previously declared variable
dblTotalSales = +total;
break;
}
case -1:
{
WriteLine("Salesperson " + name + " sold a total of $" + dblTotalSales);
break;
}
}
} while (true);
}

A local or parameter named 'Result' cannot be declared in this scope (Error CS0136)

I am learning c# and I'm trying to make a program that calculate the champions winrate in (lol) League of Legends and I'm stuck with this problem:
The error is:
Error CS0136 A local or parameter named 'Result' cannot be declared in
this scope because that name is used in an enclosing local scope to
define a local or parameter
Here is my code:
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
double TeemoWinRate = 51.33;
double AkaliWinRate = 47.56;
double YasuoWinRate = 49.73;
double KhazixWinRate = 50.94;
double YoneWinRate = 47.84;
double LuxWinRate = 50.50;
double MorgWinRater = 50.83;
double TrandyWinRate = 48.50;
double GarenWinRate = 50.50;
double TeemoGold = 11.113;
double AkaliGold = 10.880;
double YasuoGold = 11.828;
double KhazixGold = 11.541;
double YoneGold = 11.650;
double LuxGold = 9.497;
double MorgGold = 8.990;
double TrandyGold = 12.182;
double GarenGold = 11.609;
double Te = TeemoWinRate;
double A = AkaliWinRate;
double Y = YasuoWinRate;
double K = KhazixWinRate;
double Yo = YoneWinRate;
double L = LuxWinRate;
double M = MorgWinRater;
double Tr = TrandyWinRate;
double G = GarenWinRate;
Console.WriteLine("Champions Ranked WinRate From the list below");
Console.WriteLine("Akali, " +
"Yasuo, " +
"Khazix, " +
"Yone, " +
"Lux, " +
"Morg, " +
"Trandy, " +
"Garen, " +
"Teemo.");
Console.WriteLine("Note: get sure that names are written as the list");
Console.Write("Enter Champion Name : ");
string Champion = Console.ReadLine();
//------------------------------First if stattement--------------------------------------------
if (Champion == "Akali")
{
Console.WriteLine("Akali WinRate is: " + AkaliWinRate + " " + "Total Gold: " + AkaliGold);
}
else if (Champion == "Yasuo")
{
Console.WriteLine("Yasuo WinRate is: " + YasuoWinRate + " " + "Total Gold: " + YasuoGold);
}
else if (Champion == "Khazix")
{
Console.WriteLine("Khazix WinRate is: " + KhazixWinRate + " " + "Total Gold: " + KhazixGold);
}
else if (Champion == "Yone")
{
Console.WriteLine("Yone WinRate is: " + YoneWinRate + " " + "Total Gold: " + YoneGold);
}
else if (Champion == "Lux")
{
Console.WriteLine("Lux WinRate is: " + LuxWinRate + " " + "Total Gold: " + LuxGold);
}
else if (Champion == "Morg")
{
Console.WriteLine("Morg WinRate is:" + MorgWinRater + " " + "Total Gold: " + MorgGold);
}
else if (Champion == "Trandy")
{
Console.WriteLine("Trandy WinRate is: " + TrandyWinRate + " " + "Total Gold: " + TrandyGold);
}
else if (Champion == "Garen")
{
Console.WriteLine("Garen WinRate is: " + GarenWinRate + " " + "Total Gold: " + GarenGold);
}
else if (Champion == "Teemo")
{
Console.WriteLine("Teemo WinRate is" + TeemoWinRate + " " + "Total Gold: " + TeemoGold);
}
else
{
Console.WriteLine("Please Enter the name Exactly as in the list.");
return;
}
Console.WriteLine("what champion do u want to Compare with other champs");
Console.WriteLine("Type " +
"\n 1 for (Teemo) " +
"\n 2 for (Akali) " +
"\n 3 for (Yasuo) " +
"\n 4 for (khazix) " +
"\n 5 for (Yone) " +
"\n 6 for (Lux)" +
"\n 7 for (Morg)" +
"\n 8 for (Trandy)" +
"\n 9 for (Garen)");
Console.Write("First Champion: ");
double Answer1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Second Champion");
double Answer2 = Convert.ToInt32(Console.ReadLine());
//------------------------------Second if stattement--------------------------------------------
if (Answer1 == 1)
{
object Result = Answer1 - 1 + Te;
}
if (Answer1 == 2)
{
object Result = Answer1 - 2 + A;
}
if (Answer1 == 3)
{
object Result = Answer1 - 3 + Y;
}
if (Answer1 == 4)
{
object Result = Answer1 - 4 + K;
}
if (Answer1 == 5)
{
object Result = Answer1 - 5 + Yo;
}
if (Answer1 == 6)
{
object Result = Answer1 - 6 + L;
}
if (Answer1 == 7)
{
object Result = Answer1 - 7 + M;
}
if (Answer1 == 8)
{
object Result = Answer1 - 8 + Tr;
}
if (Answer1 == 9)
{
object Result = Answer1 - 9 + G;
}
//-----------------------------------Third if Statement--------------------------
if (Answer2 == 1)
{
object Result2 = Answer2 - 1 + Te;
}
if (Answer2 == 2)
{
object Result2 = Answer2 - 2 + A;
}
if (Answer2 == 3)
{
object Result2 = Answer2 - 3 + Y;
}
if (Answer2 == 4)
{
object Result2 = Answer2 - 4 + K;
}
if (Answer2 == 5)
{
object Result2 = Answer2 - 5 + Yo;
}
if (Answer2 == 6)
{
object Result2 = Answer2 - 6 + L;
}
if (Answer2 == 7)
{
object Result2 = Answer2 - 7 + M;
}
if (Answer2 == 8)
{
object Result2 = Answer2 - 8 + Tr;
}
if (Answer2 == 9)
{
object Result2 = Answer2 - 9 + G;
}
}
}
}
The error says that you cannot use Result since it is being used somewhere else try renaming it.

How to send invaild user input when using a split command

My program works correctly. The only thing I am trying to figure out is how to send an error for invalid user input. If a user types in strings or numbers without using spaces, "a * b", "12*5", how can I send an error in a split.
using System;
namespace Calculator1
{
class Program
{
static void Main(string[] args)
{
double answer;
bool Continue = true;
Console.WriteLine("\tCalculator");
Console.WriteLine("--------------------------\n");
Console.WriteLine(" Math Operations: ");
Console.WriteLine(" --------------------");
Console.WriteLine(" Multiplication: *");
Console.WriteLine(" Addition: +");
Console.WriteLine(" Subtraction: -");
Console.WriteLine(" Division: /");
while (Continue)
{
Console.WriteLine("\nEnter your equation below:");
Console.WriteLine(" For example: 5 + 5 ");
string[] values = Console.ReadLine().Split(' ');
double firstNum = double.Parse(values[0]);
string operation = (values[1]);
double secondNum = double.Parse(values[2]);
if (operation == "*")
{
answer = firstNum * secondNum;
Console.WriteLine("\n" + firstNum + " * " + secondNum + " = " + answer);
}
else if (operation == "/")
{
answer = firstNum / secondNum;
Console.WriteLine("\n" + firstNum + " / " + secondNum + " = " + answer);
}
else if (operation == "+")
{
answer = firstNum + secondNum;
Console.WriteLine("\n" + firstNum + " + " + secondNum + " = " + answer);
}
else if (operation == "-")
{
answer = firstNum - secondNum;
Console.WriteLine("\n" + firstNum + " - " + secondNum + " = " + answer);
}
else
{
Console.WriteLine("Sorry that is not correct format! Please restart!");
}
Console.WriteLine("\n\nDo you want to continue?");
Console.WriteLine("Type in Yes to continue or press any other key and then press enter to quit:");
string response = Console.ReadLine();
Continue = (response == "Yes");
}
}
}
}
Calculator
Math Operations:
Multiplication: *
Addition: +
Subtraction: -
Division: /
Enter your equation below:
For example: 5 + 5
5*5 //I want to send an error here
Unhandled Exception: System.FormatException: Input string was not in a correct format.
at System.Number.ParseDouble(ReadOnlySpan`1 value, NumberStyles options, NumberFormatInfo numfmt)
at System.Double.Parse(String s)
at Calculator1.Program.Main(String[] args)
Press any key to continue . . .
Calculator
Math Operations:
Multiplication: *
Addition: +
Subtraction: -
Division: /
Enter your equation below:
For example: 5 + 5
a * b //I also want to send an error here
Unhandled Exception: System.FormatException: Input string was not in a correct format.
at System.Number.ParseDouble(ReadOnlySpan`1 value, NumberStyles options, NumberFormatInfo numfmt)
at System.Double.Parse(String s)
at Calculator1.Program.Main(String[] args)
Press any key to continue . . .
This is probably what you need:
public static void Main(string[] args)
{
double answer;
bool Continue = true;
Console.WriteLine("\tCalculator");
Console.WriteLine("--------------------------\n");
Console.WriteLine(" Math Operations: ");
Console.WriteLine(" --------------------");
Console.WriteLine(" Multiplication: *");
Console.WriteLine(" Addition: +");
Console.WriteLine(" Subtraction: -");
Console.WriteLine(" Division: /");
while (Continue)
{
Console.WriteLine("\nEnter your equation below:");
Console.WriteLine(" For example: 5 + 5 ");
string[] values = Console.ReadLine().Split(' ');
try{
double firstNum = double.Parse(values[0]);
string operation = (values[1]);
double secondNum = double.Parse(values[2]);
switch(operation){
case "*":
answer = firstNum * secondNum;
Console.WriteLine("\n" + firstNum + " * " + secondNum + " = " + answer);
break;
case "/":
answer = firstNum / secondNum;
Console.WriteLine("\n" + firstNum + " / " + secondNum + " = " + answer);
break;
case "+":
answer = firstNum + secondNum;
Console.WriteLine("\n" + firstNum + " + " + secondNum + " = " + answer);
break;
case "-":
answer = firstNum - secondNum;
Console.WriteLine("\n" + firstNum + " - " + secondNum + " = " + answer);
break;
default:
Console.WriteLine("Sorry that is not correct format! Please restart!");
break;
}
Console.WriteLine("\n\nDo you want to continue?");
Console.WriteLine("Type in Yes to continue or press any other key and then press enter to quit:");
string response = Console.ReadLine();
Continue = (response == "Yes");
}
catch(FormatException ex){
Console.WriteLine("You entered a bad operation, try another one");
}
}
}
All you have to do is to catch a format exception that caused by a parse of a double (that isn't really a double). If you catch it, then you print an error message to the user.
I don't know what you mean by "send an error in a split". Split just splits a string.
Validate the input the do a Console.Writeline with your error message.
For validating the user input I suggest using TryParse instead of Parse. This avoids the exceptions and you can check if the input was valid.
And yes. Use a switch statement instead of your if else version. Ctrl-. should offer a refactoring for this.
Kind regards
Bernd
See this solution, please:
// Your codes
while (Continue)
{
Console.WriteLine("\nEnter your equation below:");
Console.WriteLine(" For example: 5 + 5 ");
string str = Console.ReadLine().Replace(" ", ""); // Remove all spaces
string[] values = Regex.Split(str, #"([\+\-\*\/])"); // Split numbers and operator and also keep operator
if (values.Length != 3)
{
Console.WriteLine("Expresion is not correct.");
}
else
{
double firstNum = double.Parse(values[0]);
string operation = (values[1]);
double secondNum = double.Parse(values[2]);
switch (operation)
{
case "*":
answer = firstNum * secondNum;
break;
case "/":
answer = firstNum / secondNum;
break;
case "+":
answer = firstNum + secondNum;
break;
case "-":
answer = firstNum - secondNum;
break;
default:
Console.WriteLine("Sorry that is not correct format! Please restart!");
break;
}
Console.WriteLine($"{firstNum} {operation} {secondNum} = {answer}");
Console.WriteLine("\n\nDo you want to continue?");
Console.WriteLine("Type in Yes to continue or press any other key and then press enter to quit:");
string response = Console.ReadLine();
Continue = (response.ToUpper() == "YES" || response.ToUpper() == "Y");
}
}
// Your codes

TryParse not working and if else condition not working

I am trying to make a normal form where I can convert Celsius toFahrenheit or viceversa.
private void button1_Click(object sender, EventArgs e)
{
double celsius;
double fahrenheit;
string value;
double finalValue;
bool successCelsius = double.TryParse(textBox1.Text, out celsius);
bool successFahrenheit = double.TryParse(textBox2.Text, out fahrenheit);
if (successCelsius == false)
{
label6.Text = ("ERROR: Please enter a numeric temperature to convert.");
return;
}
else
{
celsius = Convert.ToDouble(textBox1.Text);
finalValue = (celsius * 9) / 5 + 32;
label6.Text = finalValue.ToString();
label6.Text = celsius + " " + "degrees Celsius converts to" + " " + finalValue + " " + "degrees Fahrenheit";
}
if (successFahrenheit == false)
{
label6.Text = ("ERROR: Please enter a numeric temperature to convert.");
return;
}
else
{
fahrenheit = Convert.ToDouble(textBox2.Text);
finalValue = (fahrenheit - 32) * 5 / 9;
value = finalValue.ToString();
label6.Text = fahrenheit + " " + "degrees Fahrenheit converts to" + " " + finalValue + " " + "degrees Celsius";
}
}
Textbox accepted the values and displays to label6. It checks if the entered value is a double or not and then it works.
idk why tryParse isnt working.
Can you help me out? :)
The reason this code doesn't "work" is because of your code flow.
The way the code is structured right now, you have to enter both a celsius and a farenheit value or your code will display an "ERROR". If textbox1 or textbox2 are empty, your code will return false from TryParse. If you follow that logic, this code will execute (if you only enter celsius):
if (successFahrenheit == false)
{
label6.Text = ("ERROR: Please enter a numeric temperature to convert.");
return;
}
UPDATE:
You need to handle both scenarios separately...here is one way that is simple....check for one and do it....otherwise, check the other. THere are a lot of ways to "solve" this problem but this would be one of the easiest.
private void button1_Click(object sender, EventArgs e)
{
double celsius;
double fahrenheit;
string value;
double finalValue;
if (textBox1.Text.Length > 0)
{
bool successCelsius = double.TryParse(textBox1.Text, out celsius);
if (successCelsius == false)
{
label6.Text = ("ERROR: Please enter a numeric temperature to convert.");
return;
}
else
{
celsius = Convert.ToDouble(textBox1.Text);
finalValue = (celsius * 9) / 5 + 32;
label6.Text = finalValue.ToString();
label6.Text = celsius + " " + "degrees Celsius converts to" + " " + finalValue + " " + "degrees Fahrenheit";
}
}
else
{
bool successFahrenheit = double.TryParse(textBox2.Text, out fahrenheit);
if (successFahrenheit == false)
{
label6.Text = ("ERROR: Please enter a numeric temperature to convert.");
return;
}
else
{
fahrenheit = Convert.ToDouble(textBox2.Text);
finalValue = (fahrenheit - 32) * 5 / 9;
value = finalValue.ToString();
label6.Text = fahrenheit + " " + "degrees Fahrenheit converts to" + " " + finalValue + " " + "degrees Celsius";
}
}
}

How can I access information from one conditional and use it later in a different conditional?

I'm trying to access the answer from an equation (BMR)
if(gender == "F")
{
BMR = 655+(4.35 * weight) + (4.7 * height) - (4.7 * userAge );
}
else if(gender == "M")
{
BMR = 66+(6.23 * weight) + (12.7 * height) - (6.8 * userAge);
}
Console.WriteLine (name + " you entered: \nHeight: " + height + "\nWeight: " + weight + "\nAge: " + userAge + "\nGender: " + gender);
Console.WriteLine ("Your BMR is " + BMR);
and use it here
static void ProcessChoice (int c)
{
double allowedCalories;
if (c == 1) {
allowedCalories = BMR * 1.2;
Console.WriteLine ("Your allowed calories is " + allowedCalories);
} else if (c == 2) {
allowedCalories = BMR * 1.375;
Console.WriteLine ("Your allowed calories is " + allowedCalories);
} else if (c == 3) {
allowedCalories = BMR * 1.55;
Console.WriteLine ("Your allowed calories is " + allowedCalories);
} else if (c == 4) {
allowedCalories = BMR * 1.725;
Console.WriteLine ("Your allowed calories is " + allowedCalories);
} else if (c == 5) {
allowedCalories = BMR * 1.9;
Console.WriteLine ("Your allowed calories is " + allowedCalories);
}
But I keep getting errors.
Here's the entire code:
using System;
namespace Manning_C__10_23_17_Lab_Five
{
class MainClass
{
public static void Main (string[] args)
{
string name;
double height, weight;
int userAge;
string gender;
double BMR = 0;
Console.Write("Enter your name: ");
name = Console.ReadLine ();
Console.Write("Enter your height in inches: ");
height = Convert.ToDouble(Console.ReadLine ());
Console.Write ("Enter your weight in pounds: ");
weight = Convert.ToDouble(Console.ReadLine ());
Console.Write ("Enter your age: ");
userAge = Convert.ToInt32(Console.ReadLine ());
Console.Write ("Enter your gender as M or F ");
gender = Console.ReadLine ();
gender = gender.ToUpper();
if(gender == "F")
{
BMR = 655+(4.35 * weight) + (4.7 * height) - (4.7 * userAge );
}
else if(gender == "M")
{
BMR = 66+(6.23 * weight) + (12.7 * height) - (6.8 * userAge);
}
Console.WriteLine (name + " you entered: \nHeight: " + height + "\nWeight: " + weight + "\nAge: " + userAge + "\nGender: " + gender);
Console.WriteLine ("Your BMR is " + BMR);
int choice;
do {
PrintMenu ();
choice = Int32.Parse (Console.ReadLine ());
ProcessChoice (choice);
} while (choice !=6);
Console.WriteLine ("Thanks for using this system");
}
public static void PrintMenu()
{
Console.WriteLine("Main Menu");
Console.WriteLine("1. You don't exercise");
Console.WriteLine("2. You engage in light exercise one to three days a week");
Console.WriteLine("3. You exercise moderately three to 5 times a week");
Console.WriteLine("4. You exercise intensely six to seven days a week");
Console.WriteLine("5. You exercise intensely six to seven days a week " +
"and have a physically active job");
Console.WriteLine ("6. QUIT");
}
static void ProcessChoice (int c)
{
double allowedCalories;
if (c == 1) {
allowedCalories = BMR * 1.2;
Console.WriteLine ("Your allowed calories is " + allowedCalories);
} else if (c == 2) {
allowedCalories = BMR * 1.375;
Console.WriteLine ("Your allowed calories is " + allowedCalories);
} else if (c == 3) {
allowedCalories = BMR * 1.55;
Console.WriteLine ("Your allowed calories is " + allowedCalories);
} else if (c == 4) {
allowedCalories = BMR * 1.725;
Console.WriteLine ("Your allowed calories is " + allowedCalories);
} else if (c == 5) {
allowedCalories = BMR * 1.9;
Console.WriteLine ("Your allowed calories is " + allowedCalories);
}
}
}
}
MBR is declared locally in main. You will not be able to use it outside of the main method in a direct manner.
There are multiple ways to solve this issue, but since your code consists of a single class (no dependency-injection between classes is necessary), two main ways come to mind:
First way:
You can declare it at a higher scope level (in this case, MainClass):
class MainClass
{
double MBR = 0;
//...
This makes the variable accessible to the entire class, including methods in it, which in turn includes ProcessChoice.
Second way:
You can pass it to ProcessChoice as a parameter:
static void ProcessChoice (int c, double MBR) {
//...
and
int choice;
do {
PrintMenu ();
choice = Int32.Parse (Console.ReadLine ());
ProcessChoice(choice, MBR);
} //...
You need to pass the BMR value to your ProcessChoice function:
ProcessChoice (choice, BMR);
static void ProcessChoice (int c, double BMR)
{
....
}

Categories

Resources