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
Related
I am trying to make this console calculator running in loop until the user want to exit the application. How can i use a for loop with if else statements, is it possible?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Oppgave3Lesson1
{
class Program
{
static void Main(string[] args)
{
double sum = 0;
double num1;
Console.WriteLine("First number: ");
num1 = Convert.ToInt32(Console.ReadLine());
double num2;
Console.WriteLine("Second number: ");
num2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Addisjon eller Subtraksjon?");
string regneoperasjon = Console.ReadLine();
if(regneoperasjon == "Subtraksjon")
{
Console.WriteLine("Svaret til denne regneoperasjonen er: " + (sum = num1 - num2));
}
else if (regneoperasjon == "Addisjon")
{
Console.WriteLine("Svaret til denne regneoperasjonen er: " + (sum = num1 + num2));
}
Console.WriteLine("Do you want to do an another math operation?");
Console.ReadLine();
}
}
}
You can add a question for user via Console.ReadKey method and then check his answer:
do
{
double sum = 0;
double num1;
Console.WriteLine("First number: ");
num1 = Convert.ToInt32(Console.ReadLine());
double num2;
Console.WriteLine("Second number: ");
num2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Addisjon eller Subtraksjon?");
string regneoperasjon = Console.ReadLine();
if(regneoperasjon == "Subtraksjon")
{
Console.WriteLine("Svaret til denne regneoperasjonen er: " + (sum = num1 - num2));
}
else if (regneoperasjon == "Addisjon")
{
Console.WriteLine("Svaret til denne regneoperasjonen er: " + (sum = num1 + num2));
}
Console.WriteLine("Calculate the next operation (Y/N)?");
}
while(Console.ReadKey(true).Key == ConsoleKey.Y);
So you get the output like in the screenshot below:
Try following. I made the writlines a write :
namespace Oppgave3Lesson1
{
class Program
{
static void Main(string[] args)
{
while(true)
{
double sum = 0;
double num1;
Console.Write("First number: (or Exit)");
string firstNumStr = Console.ReadLine();
if(firstNumStr == "Exit") break;
num1 = Convert.ToInt32(firstNumStr);
double num2;
Console.Write("Second number: ");
num2 = Convert.ToInt32(Console.ReadLine());
Console.Write("Addisjon eller Subtraksjon?");
string regneoperasjon = Console.ReadLine();
if(regneoperasjon == "Subtraksjon")
{
Console.Write("Svaret til denne regneoperasjonen er: " + (sum = num1 - num2));
}
else if (regneoperasjon == "Addisjon")
{
Console.Write("Svaret til denne regneoperasjonen er: " + (sum = num1 + num2));
}
}
A for loop is used when you know the (maximum) number of iterations upfront.
In your scenario, a while loop is more apropriate.
do
{
// Perform your logic here
Console.WriteLine("Press any key to continue; Q to quit");
var key = Console.ReadKey();
}while( key != ConsoleKey.Q );
or, use an endless while - loop and break from the loop on a certain condition:
while( true )
{
// Perform your logic here
Console.WriteLine("Press any key to continue; Q to quit");
var key = Console.ReadKey();
if( key == ConsoleKey.Q )
{
break;
}
}
is there's something wrong with my code below?
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int num1 = 0, num2 = 0, rslt = 0;
char oprtr;
Console.Write("Enter calculation: ");
num1 = Convert.ToInt32(Console.Read());
oprtr = Console.ReadKey().KeyChar;
num2 = Convert.ToInt32(Console.Read());
switch (oprtr)
{
case '+':
rslt = num1 + num2;
break;
case '-':
rslt = num1 - num2;
break;
case '*':
rslt = num1 * num2;
break;
case '/':
rslt = num1 / num2;
break;
default:
break;
}
Console.Write("rslt: {0}", rslt);
Console.WriteLine();
Console.ReadKey();
return;
}
}
}
after i compile and run it, the result is 0
it looks like there's nothing wrong with my code.
don't know what's wrong with my code
You need to use Console.ReadLine() instead of Console.Read(). Console.Read() reads the pressed key code not the value.
Replace the following lines
Console.Write("Enter calculation: ");
num1 = Convert.ToInt32(Console.Read());
oprtr = Console.ReadKey().KeyChar;
num2 = Convert.ToInt32(Console.Read());
with
Console.Write("Enter calculation");
Console.Write("\nEnter 1st Operand: ");
num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Operator: ");
oprtr = Console.ReadKey().KeyChar;
Console.Write("\nEnter 2nd Operand: ");
num2 = Convert.ToInt32(Console.ReadLine());
EDIT:
Use int.TryParse method to avoid exception because if user press any alphabet or special character then it cannot be store into integer.
Example
int num1;
if (!int.TryParse(Console.ReadLine(), out num1)
{
Console.WriteLine("Invalid Number");
}
else
{
//num1 is ready for calculations
}
Another thing, you should avoid integers because for division, integer/integer = integer, i-e 5/2 = 2 but it should 2.5
using System;
namespace prac4b
{
class prac4b
{
static void Main(string[] args)
{
int number1, number2, result;
char action;
string tempVal = "";
bool parseAttempt = false;
// ask for first number
Console.ReadLine();
Console.Write("Enter number > ");
//testing if integer with TryParse
tempVal = Console.ReadLine();
parseAttempt = Int32.TryParse(tempVal, out number1);
// if not a number
if (parseAttempt == false)
{
Console.WriteLine("You have not entered a number, application will now exit.");
Environment.Exit(0);
}
//if true, continue, ask for number2
if (parseAttempt == true)
{
//asking for number
Console.Write("Enter another number > ");
tempVal = Console.ReadLine(); //storing number temporailiy for checking
parseAttempt = Int32.TryParse(tempVal, out number2); //checking number2 if integer
//if not a number
if (parseAttempt == false)
{
Console.WriteLine("ERROR you have not entere a valid integer");
Environment.Exit(0);
}
//if true, continue, ask for action(+*-+)
Console.WriteLine("Action (*/+-) > ");
action = Console.ReadLine();
switch (action) //switch statement for action list
{
case "+":
Console.WriteLine("Result is > ", number1 + number2);
break;
case "-":
Console.WriteLine("Result is > ", number1 - number2);
break;
case "*":
Console.WriteLine("Result is > ", number1 * number2);
break;
case "/":
Console.WriteLine("Result is > ", number1 / number1);
break;
default:
Console.WriteLine("ERROR INVALID INPUT");
Environment.Exit(0);
break;
}
Console.WriteLine();
}
}
}
}
I'm trying to get this switch statement to work but it keeps coming up with error, can't change string to char. I don't see where I have tried to change a string to char.
Use
action = Console.ReadKey().KeyChar;
instead of
action = Console.ReadLine();
&
case "+": to case '+':
you declare
char action;
as a char Type but
switch (action)
{
case "+": // here you compare it with a string.
....
case "-": // here you compare it with a string.
....
case "*": // here you compare it with a string.
....
case "/": // here you compare it with a string.
...
action = Console.ReadLine(); //here you try to set a string
replace char action; with string action;
You may find useful to remove swicth at all and implement a dictionary instead:
Dictionary<String, Func<Double, Double, Double>> Actions = new {
{"+", (x, y) => x + y},
{"-", (x, y) => x - y},
{"*", (x, y) => x * y},
{"/", (x, y) => x / y},
};
...
Console.WriteLine("Action (*/+-) > ");
action = Console.ReadLine();
Func<Double, Double, Double> func;
if (Actions.TryGetValue(action, out func))
Console.WriteLine("Result is > ", func(number1, number2));
else
Console.WriteLine("ERROR INVALID INPUT");
if you have a lot of actions (e.g. power **, reminder % etc.) dictionary implemenation is more readable.
using System;
namespace prac4b
{
class prac4b
{
static void Main(string[] args)
{
int number1, number2, result;
char action;
string tempVal = "";
bool parseAttempt = false;
// ask for first number
Console.ReadLine();
Console.Write("Enter number > ");
//testing if integer with TryParse
tempVal = Console.ReadLine();
parseAttempt = Int32.TryParse(tempVal, out number1);
// if not a number
if (parseAttempt == false)
{
Console.WriteLine("You have not entered a number, application will now exit.");
Environment.Exit(0);
}
//if true, continue, ask for number2
if (parseAttempt == true)
{
//asking for number
Console.Write("Enter another number > ");
tempVal = Console.ReadLine(); //storing number temporailiy for checking
parseAttempt = Int32.TryParse(tempVal, out number2); //checking number2 if integer
//if not a number
if (parseAttempt == false)
{
Console.WriteLine("ERROR you have not entere a valid integer");
Environment.Exit(0);
}
//if true, continue, ask for action(+*-+)
Console.WriteLine("Action (*/+-) > ");
var readaction = Console.ReadLine();
string actionString = readaction.ToString();
switch (actionString) //switch statement for action list
{
case "+":
Console.WriteLine("Result is > ", number1 + number2);
break;
case "-" :
Console.WriteLine("Result is > ", number1 - number2);
break;
case "*" :
Console.WriteLine("Result is > ", number1 * number2);
break;
case "/" :
Console.WriteLine("Result is > ", number1 / number1);
break;
default :
Console.WriteLine("ERROR INVALID INPUT");
Environment.Exit(0);
break;
}
Console.WriteLine();
}
}
}
}
these are the variables I used to save data in
int num1 = int.Parse(Console.ReadLine());
string sign = Console.ReadLine();
int num2 = int.Parse(Console.ReadLine());
the if statement that check the input's
how to make it simple
if (sign == "+")
{
Console.WriteLine(num1 + num2);
}
else if (sign == "-")
{
Console.WriteLine(num1 - num2);
}
else if (sign == "*")
{
Console.WriteLine(num1 * num2);
}
else if (sign == "/")
{
Console.WriteLine(num1 / num2);
}
else
{
Console.WriteLine("Wrong operation sign ...");
}
Console.ReadLine();
How to show the output in the form num1 sign num2 = num3 e.g. "6 + 4 = 10" in the console window?
Use string formatting:
Console.WriteLine("{0} {1} {2} = {3}",num1, sign, num2, num1 + num2);
For more information take a look at: Composite Formatting and also Console.WriteLine(String, Object) Method
Save your result to a variable outside of your if/else statement so that you can "dynamically" build your output at the end.
var result = 0;
if (sign == "+")
{
result = num1 + num2;
}
else if (sign == "-")
{
result = num1 - num2;
}
else if (sign == "*")
{
result = num1 * num2;
}
else if (sign == "/")
{
result = num1 / num2;
}
else
{
Console.WriteLine("Wrong operation sign ...");
}
Console.WriteLine("{0}{1}{2}={3}", num1, sign, num2, result);
Console.ReadLine();
To print out the result u can do
Console.WriteLine("{0}{1}{2}={3}", num1, sign, num2, result)
where result is the result of the operation. (e.g. 6 in your example)
"how to make it simple?"
You can abuse the DataTable.Compute method:
var answer = new DataTable().Compute(num1.ToString() + sign + num2.ToString(), null);
"How to show the output..."
See String.Format / console.WriteLine overload as mentioned by Selman22, eg:
Console.WriteLine("{0} {1} {2} = {3}",num1, sign, num2, answer);
How your program could be written:
Console.WriteLine("Please type a simple sum:");
string sum = Console.Readline();
var answer = new DataTable().Compute(sum, null);
Console.WriteLine("{0} = {1}",sum, answer);
Console.Readline();
Hi it is just a simple calculator. I want to allow user to enter "N" or "n" after I asked them if they want to make an another conversion.
(Enter Y to make an another conversion/Enter N return to Main menu). How do I do that?
static int LengthCalculator() {
int LengthCalculatorOption;
string AnotherConversion = null;
double Centimetres = 0.0, Feet = 0.0, Inches = 0.0, TotalInches = 0.0;
const double CENTIMETRES_PER_INCH = 2.54, INCHES_PER_FOOT = 12;
do {
LengthCalculatorMenu();
LengthCalculatorOption = ValidLengthCalculatorReadOption();
if (LengthCalculatorOption == 1) {
Console.WriteLine("Please Enter the Centimetres(cm) that you wish to convert to feet and inches:");
Centimetres = double.Parse(Console.ReadLine());
TotalInches = (Centimetres / CENTIMETRES_PER_INCH); // This will take a floor function of Centimetres/2.54
Feet = (TotalInches - TotalInches % INCHES_PER_FOOT) / INCHES_PER_FOOT; // This will make it divisible by 12
Inches = TotalInches % INCHES_PER_FOOT; // This will give you the remainder after you divide by 12
Console.WriteLine("\nThe equivalent in feet and inches is {0} ft {1} ins", Feet, Inches);
Console.Write("\nWould you like to make an another conversion? \n\n(Enter Y to make an another conversion/Enter any key return to Main menu):");
AnotherConversion = Console.ReadLine();
} else if (LengthCalculatorOption == 2) {
Console.WriteLine("Please Enter the Feet:");
Feet = double.Parse(Console.ReadLine());
Console.WriteLine("Please Enter the Inches:");
Inches = double.Parse(Console.ReadLine());
Centimetres = ((Feet * INCHES_PER_FOOT) + Inches) * CENTIMETRES_PER_INCH;
Console.WriteLine("\nThe equivalent in centimetres is {0}cm", Centimetres);
Console.Write("\nWould you like to make an another conversion? \n\n(Enter Y to make an another conversion/Enter any key return to Main menu):");
AnotherConversion = Console.ReadLine();
}
} while (AnotherConversion == "y" || AnotherConversion == "Y");
return LengthCalculatorOption;
}//End LenthCalculator
static void LengthCalculatorMenu() {
string LengthCalculatorMenu = ("Enter 1) Convert Centimetres to Feet and Inches:"
+ "\nEnter 2) Convert feet and inches to centimetres:");
Console.WriteLine(LengthCalculatorMenu);
} // End LengthCalculatorMenu
static int ValidLengthCalculatorReadOption() {
int LengthCalculatorOption;
bool ValidLengthCalculatorOption = false;
do {
LengthCalculatorOption = int.Parse(Console.ReadLine());
if ((LengthCalculatorOption >= 1) && (LengthCalculatorOption <= 2)) {
ValidLengthCalculatorOption = true;
} else {
ValidLengthCalculatorOption = false;
} // end if
if (!ValidLengthCalculatorOption) {
Console.WriteLine("\n\t Option must be 1 or 2, Please Re-Enter your Option");
LengthCalculatorMenu();
} //end if
} while (!ValidLengthCalculatorOption);
return LengthCalculatorOption;
}// End LengthCalculatorReadOption
static int ReadMainMenuOption() {
int option = 0;
bool ValidMainMenuOption = false;
do {
option = int.Parse(Console.ReadLine());
if ((option >= 1) && (option <= 5)) {
ValidMainMenuOption = true;
} else {
ValidMainMenuOption = false;
} // end if
if (option == 1) {
LengthCalculator();
} else if (option == 2) {
} else if (option == 3) {
} else if (option == 4) {
} else if (option == 5) {
} // end if
if (!ValidMainMenuOption) {
Console.WriteLine("\n\t\a Option must be 1,2,3,4 or 5");
DisplayMenu();
} //end if
} while (!ValidMainMenuOption);
return option;
} //end ReadOption
/* Displays Main Menu
* Precondition:true
* postcondition: DisplayMenu displayed
*/
static void DisplayMenu() {
string mainMenu = "\n1)Length Calculator"
+ "\n2)Body Mass Index Calculator"
+ "\n3)Waist to Height Calculator"
+ "\n4)Fuel Consumption Calculator"
+ "\n5)Exit the Calculator"
+ "\n\nEnter your option(1,2,3,4 or 5 to exit):";
Console.Write(mainMenu);
} //end DisplayMenu
static void Main(string[] args) {
const int Exit = 5;
int menuOption;
do {
DisplayMenu();
menuOption = ReadMainMenuOption();
} while (menuOption != Exit);
Console.Write("Thank you for using this Calculator. Press any Key to Exit");
//terminating message
Console.ReadKey();
}//end Main
You can make a separate method that will handle user input. For example, this method will determine if the user has entered a Y or N. If they haven't it re-prompt them to do so:
static bool AnotherConversion()
{
var prompt = "\nWould you like to make an another conversion? \n\n(Enter (Y) to make another conversion or (N) to return to the Main Menu):";
Console.WriteLine(prompt);
while (true)
{
var userInput = Console.ReadLine();
if (String.Compare("Y", userInput, StringComparison.Ordinal)
{
return true;
}
else if (String.Compare("N", userInput, StringComparison.Ordinal)
{
return false;
}
else
{
// Invlalid input, re-prompt
Console.WriteLine("Invalid Input, please enter or (Y) or (N)!");
Console.WriteLine(prompt);
}
}
}
You can them simply update your do/while loop so that the condition is based on the AnotherConversion method. This will allow the prompt to be asked whenever a calculation is done:
static int LengthCalculator() {
....
do {
.....
} while (AnotherConversion());
return LengthCalculatorOption;
}//End LenthCalculator
Call to this method in the place you want:
static bool shouldMakeAnotherConversion()
{
repeatQuestion:
// This shows the question to the user
Console.Write("Do you want to make another conversion (Y/N)? ");
ConsoleKeyInfo answer = Console.ReadKey(true);
switch (answer.Key)
{
case ConsoleKey.Y: return true;
case ConsoleKey.N: return false;
}
//If the user types any other key, the program will repeat the question
Console.WriteLine();
goto repeatQuestion;
}
class Program
{
public static void parameter(int num1, int num2, out int add, out int sub, out int mul, out float div)
{
add = num1 + num2;
sub = num1 - num2;
mul = num1 * num2;
div = (float)num1 / num2;
}
static void Main(string[] args)
{
int num1, num2;
int add, sub, mul;
float div;
Console.Write("Enter 1st number\t");
num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("\nEnter 2nd number\t");
num2 = Convert.ToInt32(Console.ReadLine());
Program.parameter(num1, num2, out add, out sub, out mul, out div);
Console.WriteLine("\n\n{0} + {1} = {2}", num1, num2, add);
Console.WriteLine("{0} - {1} = {2}", num1, num2, sub);
Console.WriteLine("{0} * {1} = {2}", num1, num2, mul);
Console.WriteLine("{0} / {1} = {2}", num1, num2, div);
Console.ReadLine();
}
}
}
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Type you first number :");
Console.WriteLine("Type you second number :");
Console.WriteLine("Enter the operation + (addition), - (soustraction), * (multiplication), / (division)");
string stringOperation = Console.ReadLine();
switch (operation)
{
case 1:
result = firstNumber + secondNumber;
break;
case 2:
result = firstNumber - secondNumber;
break;
case 3:
result = firstNumber * secondNumber;
break;
case 4:
result = firstNumber / secondNumber;
break;
}
}
}
}