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();
Related
We need to create a simple calculator using parameterized constructor/methods
//I declared some local variables for the parameter
Console.WriteLine("Enter first number: ");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter second number: ");
double num2= Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter operator: ");
char operation = Convert.ToChar(Console.ReadLine());
double result;
//I used switch-case for the method
static void Calcu(char operation, double num1, double num2, double result)
{
switch (operation)
{
case '+':
result = num1 + num2;
Console.WriteLine("Sum: " + result);
break;
case '-':
result = num1 - num2;
Console.WriteLine("Difference: "+ result);
break;
case '*':
result = num1 * num2;
Console.WriteLine("Product: "+ result);
break;
case '/':
result = num1 / num2;
Console.WriteLine("Quotient: "+ result);
break;
default:
Console.WriteLine("Invalid Operator");
break;
}
}
I am having trouble in getting the result from the method and printing the result outside the method
You need to specify that your method returns something, right now it returns nothing void.
Changing void to double signals that this method will return a double.
You are also passing the result into the Calcu() method which I doubt you want. You should specify the result as a variable within the method then return that variable.
I'm guessing this is what you mean.
static double Calcu(char operation, double num1, double num2)
{
double result;
switch (operation)
{
case '+':
result = num1 + num2;
Console.WriteLine("Sum: " + result);
break;
case '-':
result = num1 - num2;
Console.WriteLine("Difference: "+ result);
break;
case '*':
result = num1 * num2;
Console.WriteLine("Product: "+ result);
break;
case '/':
result = num1 / num2;
Console.WriteLine("Quotient: "+ result);
break;
default:
Console.WriteLine("Invalid Operator");
break;
}
return result
}
Then take in your variables, and then pass them to the method.
//I declared some local variables for the parameter
Console.WriteLine("Enter first number: ");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter second number: ");
double num2= Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter operator: ");
char operation = Convert.ToChar(Console.ReadLine());
Calcu(operation, num1, num2);
EDIT: sorry terrible formatting
I'm a complete noob at programming and I was wondering where i went wrong with this simple calculator i was trying. I can't seem to get the program to run the method. I think it may ave something to do with how i expressed it in the if statement but no matter what i try, i just can't seem to get it to work.
namespace NewNew
{
class Program
{
private static double Ans;
private static double num1;
private static double num2;
private static string op;
static void Main(string[] args)
{
Console.Write("Enter First Number: ");
double num1 = Convert.ToDouble(Console.ReadLine());
string op = Console.ReadLine();
if (op == "+" || op == "-" || op == "/" || op == "*")
{
Calc;
}
else
{
Console.WriteLine("Invalid Operator");
}
Console.WriteLine(Ans);
Console.ReadLine();
}
static double Calc(double Ans)
{
Console.Write("Enter Second Number: ");
double num2 = Convert.ToDouble(Console.ReadLine());
if (op == "+")
{
Ans = num1 + num2;
}
else if (op == "-")
{
Ans = num1 - num2;
}
else if (op == "/")
{
Ans = num1 / num2;
}
else if (op == "*")
{
Ans = num1 * num2;
}
return Ans;
}
}
Alright I see where you were going but seems like you got off track.
You declared all of these as global:
private static double Ans;
private static double num1;
private static double num2;
private static string op;
Each time you re-declared new variables for each with the same name. You never used those existing, static variables.
double num1 = Convert.ToDouble(Console.ReadLine());
string op = Console.ReadLine();
I think this is what you were after:
namespace NewNew
{
class Program
{
private static double Ans;
private static double num1;
private static double num2;
private static string op;
static void Main(string[] args)
{
Console.Write("Enter First Number: ");
num1 = Convert.ToDouble(Console.ReadLine());
op = Console.ReadLine();
if (op == "+" || op == "-" || op == "/" || op == "*")
{
Calc();
}
else
{
Console.WriteLine("Invalid Operator");
}
Console.WriteLine(Ans);
Console.ReadLine();
}
static double Calc()
{
Console.Write("Enter Second Number: ");
num2 = Convert.ToDouble(Console.ReadLine());
if (op == "+")
{
Ans = num1 + num2;
}
else if (op == "-")
{
Ans = num1 - num2;
}
else if (op == "/")
{
Ans = num1 / num2;
}
else if (op == "*")
{
Ans = num1 * num2;
}
return Ans;
}
}
}
Though, I would recommend using local variables vs using them globally across the entire class.
Try passing num1 to your call to Calc:
if (op == "+" || op == "-" || op == "/" || op == "*")
{
Calc(num1);
}
Additionally, you should name the parameter in Calc to num1 instead of Ans, so you can reference its value in the Calc method:
static double Calc(double num1)
{
// ...
}
Method calls require parenthesises after its name e.g MethodName(). In this case you also need to pass a double e.g Calc(2.2) because you specify that in the method definition
first of all, I correct your naming convention for best practices always camel case for local variable name and name your variable properly so it will easy for you to read. you may learn on this link for naming convention https://github.com/ktaranov/naming-convention/blob/master/C%23%20Coding%20Standards%20and%20Naming%20Conventions.md
Second make sure you use your declared variables, because in your code you didn't use these variable:
private static double Ans;
private static double num1;
private static double num2;
private static string op;
and you declare another so that's why you got confuse.
I rewrite your code to more readable code so it will easy to you to understand. But this was a good start keep on writing a code. Be a happy coder :)
private static double answer;
private static double firstNumber;
private static double secondNumber;
private static string operation;
static void Main(string[] args)
{
Console.Write("Enter First Number: ");
firstNumber = Convert.ToDouble(Console.ReadLine());
operation = Console.ReadLine();
if (operation == "+" || operation == "-" || operation == "/" || operation == "*")
{
Calc();
}
else
{
Console.WriteLine("Invalid Operator");
}
Console.WriteLine(answer);
Console.ReadLine();
}
static double Calc()
{
Console.Write("Enter Second Number: ");
secondNumber = Convert.ToDouble(Console.ReadLine());
if (operation == "+")
{
answer = firstNumber + secondNumber;
}
else if (operation == "-")
{
answer = firstNumber - secondNumber;
}
else if (operation == "/")
{
answer = firstNumber / secondNumber;
}
else if (operation == "*")
{
answer = firstNumber * secondNumber;
}
return answer;
}
Change your method as below
static void Calc()
{
Console.Write("Enter Second Number: ");
num2 = Convert.ToDouble(Console.ReadLine());
if (op == "+")
{
Ans = num1 + num2;
}
else if (op == "-")
{
Ans = num1 - num2;
}
else if (op == "/")
{
Ans = num1 / num2;
}
else if (op == "*")
{
Ans = num1 * num2;
}
}
in your main method add parenthesis in your function call and remove the re declaration of variables
static void Main(string[] args)
{
Console.Write("Enter First Number: ");
num1 = Convert.ToDouble(Console.ReadLine());
op = Console.ReadLine();
if (op == "+" || op == "-" || op == "/" || op == "*")
{
Calc();
}
else
{
Console.WriteLine("Invalid Operator");
}
Console.WriteLine(Ans);
Console.ReadLine();
}
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
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();
}
}
}
}