C# console application calculation loops - c#

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

Related

C#, How to return a string and Int from the same method

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

C# Calculator: How do i store the answer from a previous calculation to be used again? [closed]

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.

C# While loop only returns one iteration regardless of input

Trying to write a simple set of code that converts from fahrenheit into celsius, and there are three set conditions that determines what happens. Either it's too cold, just right or too hot. For some reason no matter the input, it will only reply and say it is too cold. I can't really figure out why.
Here's the code so far;
{
class Program
{
static int FahrenheitToCelsius(int fahrenheit)
{
int celsius = ((fahrenheit - 32) * 5 / 9);
return celsius;
}
static void Main(string[] args)
{
Console.WriteLine("Please enter the desired temperature: ");
int fahrenheit = Convert.ToInt32(Console.ReadLine());
int celsius = FahrenheitToCelsius(fahrenheit);
while (celsius != 75)
if (celsius < 73)
{
Console.WriteLine("Too cold! Please enter a warmer temperature.");
Console.ReadLine();
}
else if (celsius > 77)
{
Console.WriteLine("Too warm! Please enter a colder temperature.");
Console.ReadLine();
}
else if (celsius == 75)
{
Console.WriteLine("Optimal input! Begin heating up.");
break;
}
else
{
Console.WriteLine("Invalid input! Please input a temperature.");
}
}
}
}
maybe You only getting same message because you haven't change value of celsius
static int FahrenheitToCelsius(int fahrenheit)
{
int celsius = ((fahrenheit - 32) * 5 / 9);
return celsius;
}
static void Main(string[] args)
{
Console.WriteLine("Please enter the desired temperature: ");
int fahrenheit = Convert.ToInt32(Console.ReadLine());
int celsius = FahrenheitToCelsius(fahrenheit);
Console.WriteLine("C = " + celsius);
int i = 0;
while (celsius != 75) {
if (i>0)
{
int x = Convert.ToInt32(Console.ReadLine());
celsius = FahrenheitToCelsius(x);
}
if (celsius < 73)
{
Console.WriteLine("Too cold! Please enter a warmer temperature.");
}
else if (celsius > 77)
{
Console.WriteLine("Too warm! Please enter a colder temperature.");
}
else if (celsius == 75)
{
Console.WriteLine("Optimal input! Begin heating up.");
break;
}
else
{
Console.WriteLine("Invalid input! Please input a temperature.");
}
i++;
}
}
}
First, Fix your conversion. When converting from one unit to an other one should not remove the decimal value.
static double FahrenheitToCelsius(double f) => (f - 32) * 5.0 / 9.0;
Now lets talk about your if/else. In your code
T <= 163 is too cold;
T = 164,165,166,169,170 are all invalid Temperature;
T >= 171 is too hot;
There is not reason to have those invalid right in the middle of the range.
And there is no explanation on Invalid temp so just drop it.
Is there a number that can satisfy multiple of those condition?
x < 73, x > 77, x ==75...
We can safely drop all the else.
if (tempC < 73)
{
Console.WriteLine("Too cold! Please enter a warmer temperature.\n");
}
if (tempC > 77)
{
Console.WriteLine("Too warm! Please enter a colder temperature.\n");
}
if (tempC == 75)
{
Console.WriteLine("Optimal input! Begin heating up.\n");
}
Using a Do/While loop we have :
static void Main(string[] args)
{
double tempC , tempF;
do
{
Console.WriteLine("Please enter the desired temperature: ");
tempF = Convert.ToDouble(Console.ReadLine());
tempC = FahrenheitToCelsius(tempF);
Console.WriteLine($"{tempF,4:F}°F, {tempC,4:F}°C");
if (tempC < 73)
{
Console.WriteLine("Too cold! Please enter a warmer temperature.\n");
}
if (tempC > 77)
{
Console.WriteLine("Too warm! Please enter a colder temperature.\n");
}
if (tempC == 75)
{
Console.WriteLine("Optimal input! Begin heating up.\n");
}
}
while (tempC != 75);
}
Nb renamed the variable from Fahrenheit and Celsius to tempF and tempC.
Temperatur unit find is the while are : C, F, K, R, De, N, Re, Ro.
I'm not sure one can write the name of those without google.

Try-Catch Formatting C#

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

BMI[C#] Calculator featuring a regular calculator -- Issues when it comes to the main calculator (Schoolboy Error?)

So I recently made a calculator as part of my A-Level computing class, and it worked fine then my teacher told me to add a BMI Calculator, which again works fine, however now the issue is the calculator does not run. Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Calculator1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello! Type BMI to head to the BMI Calulator");
Console.WriteLine("If you want a calculator -- Here are your commands:");
Console.WriteLine("TIMES - ADD - SUBTRACT - DIVIDE");
string text = Console.ReadLine();
if (text == "BMI")
{
Console.Clear();
Console.WriteLine("Welcome to the BMI Calcualtor! Please enter your height (M)");
string height = Console.ReadLine();
Double height1 = Convert.ToDouble(height);
Double height2 = height1 * height1;
Double heightB = Convert.ToDouble(height2);
Console.Clear();
Console.WriteLine("Please enter your Weight(KG)");
string weight = Console.ReadLine();
int weight1 = Convert.ToInt32(weight);
Double weightA = Convert.ToDouble(weight1);
Double fbmi = weightA / heightB;
Console.WriteLine(fbmi);
if (fbmi < 18.5)
{
Console.WriteLine("UnderWeight");
Console.ReadLine();
}
if (fbmi > 18.5&& fbmi < 25.0)
{
Console.WriteLine("Normal");
Console.ReadLine();
}
if (fbmi > 25.0 && fbmi < 29.9)
{
Console.WriteLine("OverWeight");
Console.ReadLine();
}
if (fbmi > 29.9 && fbmi < 40.0)
{
Console.WriteLine("Obese");
Console.ReadLine();
}
if (fbmi > 40.1)
{
Console.WriteLine("Extremely Obese");
Console.ReadLine();
}
if (text == "TIMES")
{
Console.WriteLine("Enter your first number");
string number = Console.ReadLine();
int NumberA = Convert.ToInt32(number);
Console.WriteLine("Enter your second number");
string number1 = Console.ReadLine();
int NumberB = Convert.ToInt32(number1);
Console.WriteLine("");
Console.WriteLine("============");
Console.WriteLine("ANSWER");
Console.WriteLine("============");
Console.WriteLine(NumberA * NumberB);
Console.ReadLine();
}
if (text == "ADD")
{
Console.WriteLine("Enter your first number");
string number = Console.ReadLine();
int NumberA = Convert.ToInt32(number);
Console.WriteLine("Enter your second number");
string number1 = Console.ReadLine();
int NumberB = Convert.ToInt32(number1);
Console.WriteLine("");
Console.WriteLine("============");
Console.WriteLine("ANSWER");
Console.WriteLine("============");
Console.WriteLine(NumberA + NumberB);
Console.ReadLine();
}
if (text == "SUBTRACT")
{
Console.WriteLine("Enter your first number");
string number = Console.ReadLine();
int NumberA = Convert.ToInt32(number);
Console.WriteLine("Enter your second number");
string number1 = Console.ReadLine();
int NumberB = Convert.ToInt32(number1);
Console.WriteLine("");
Console.WriteLine("============");
Console.WriteLine("ANSWER");
Console.WriteLine("============");
Console.WriteLine(NumberA - NumberB);
Console.ReadLine();
}
if (text == "DIVIDE")
{
Console.WriteLine("Enter your first number");
string number = Console.ReadLine();
int NumberA = Convert.ToInt32(number);
Console.WriteLine("Enter your second number");
string number1 = Console.ReadLine();
int NumberB = Convert.ToInt32(number1);
Console.WriteLine("");
Console.WriteLine("============");
Console.WriteLine("ANSWER");
Console.WriteLine("============");
Console.WriteLine(NumberA / NumberB);
Console.ReadLine();
}
}
}
}
}
So, any help is appreciated :)
It looks like your { } are a bit out of place:
You should add a } after:
if (fbmi > 40.1)
{
Console.WriteLine("Extremely Obese");
Console.ReadLine();
}
Then remove one from the very end.
Then way it is laid out now, your other if statments are within the if statement for BMI.

Categories

Resources