how to convert a string into operator in c# [duplicate] - c#

This question already has answers here:
Is there a string math evaluator in .NET?
(18 answers)
Closed 2 years ago.
Im trying to convert a string called symbol into an operator (+ = - /) for a calculator. Instead of having only one symbol that is already chosen before, the user will choose what symbol to use (the result wont work since its not an operator).
class Program
{
static void Main(string[] args)
{
double num01;
double num02;
string symbol;
Console.WriteLine("Input a number");
num01=Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Write the second number");
num02=Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Choose a mathematic symbol");
symbol=Convert.ToString(Console.ReadLine());
double result = ( num01 symbol num02 );
Console.WriteLine ("The result is " + result);
Console.ReadKey();
}
}

You should create an additional method that will take your symbol and integers and perform the necessary calculation.
private int Calculate(string operator, int number1, int number2)
{
if (operator == "+")
{
return number1 + number2;
}
else if (operator == "-")
{
return number1 - number2;
}
else if (operator == "*")
{
return number1 * number2;
}
else if (operator == "/")
{
return number1 / number2;
}
else
{
throw new ArgumentException("Unexpected operator string: " + operator);
}
}

Related

My variable is a char but it's telling me to convert it to char from string

I've been learning C#, but after some angry Googling I still can't figure out what's going on here. I wanted to code a simple command-line program, but one of my variables is somehow not working correctly and I don't understand why. Here is the part of the code relating to the error:
Console.Write("What operation? (Add, Subtract, Multiply, Divide)");
char Operator = Convert.ToChar(Console.ReadLine());
if (Operator = "A")
{
Answer = (Num1 + Num2);
}
else if (Operator = "S")
{
Answer = (Num1 - Num2);
}
else if (Operator = "M")
{
Answer = (Num1 * Num2);
}
else if (Operator = "D")
{
Answer = (Num1 / Num2);
}
else
{
Console.WriteLine("Invalid operator");
}
Console.WriteLine("The answer is " + Answer);
VS just tells me that I can't implicitly convert from string to char, but the Operator variable has always been a char. I converted the ReadLine string for the variable, as the input would only be one character.
Your tests should be if (Operator == 'A') so you are comparing to a char rather than a string.
Also, if your input is invalid, Answer will be unassigned at the last line.
Double quotes in C# mean that you are creating string literal, you should use single quotes to specify that it is char. You can read more about chars and strings here and here
Console.Write("What operation? (Add, Subtract, Multiply, Divide)");
char Operator = Convert.ToChar(Console.ReadLine());
if (Operator == 'A')
{
}
else if (Operator == 'S')
{
}
else if (Operator == 'M')
{
}
else if (Operator == 'D')
{
}
else
{
Console.WriteLine("Invalid operator");
}
if operator compares the value with "==" (Comparision Operator).
Please try this code:
using System.IO;
using System;
class Program
{
static void Main()
{
int Num1=6, Num2 =2, Answer =0;
Console.Write("What operation? (Add, Subtract, Multiply, Divide)");
char Operator = Convert.ToChar(Console.ReadLine());
if (Operator == 'A')
{
Answer = (Num1 + Num2);
}
else if (Operator == 'S')
{
Answer = (Num1 - Num2);
}
else if (Operator == 'M')
{
Answer = (Num1 * Num2);
}
else if (Operator == 'D')
{
Answer = (Num1 / Num2);
}
else
{
Console.WriteLine("Invalid operator");
}
Console.WriteLine("The answer is " + Answer);
}
}
char Operator = Convert.ToChar(Console.ReadLine());
this will work only you enter 1 character like A, D, S, M . When your inputs will be like Add, Subtract, Multiply, Divide you have to take first letter of them. For that you can use
char Operator = Console.ReadLine().toString()[0];
since every string variable is a char array you can take first index of it.

C# DivideByZeroException won't execute [duplicate]

This question already has answers here:
Divide by zero and no error? [duplicate]
(2 answers)
Why does this method return double.PositiveInfinity not DivideByZeroException?
(4 answers)
Inconsistency in divide-by-zero behavior between different value types
(5 answers)
Closed 2 years ago.
I have written the code below. And I want the output to be :Error!Division by zero..
But my output is: infinity.
What's the problem with this code?
//This is the class:
public class Exc
{
private double number1;
private double number2;
public double result;
public Exc(double n1,double n2)
{
this.number1 = n1;
this.number2 = n2;
}
public void Div(double number1, double number2)
{
try
{
result = number1 / number2;
Console.WriteLine(result);
}
catch (DivideByZeroException e)
{
Console.WriteLine("Error! Division by zero.{0}",e);
}
}
}
//This is my program:
static void Main(string[] args)
{
Console.WriteLine("Enter the first number:");
double n1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter the second number:");
double n2 = Convert.ToDouble(Console.ReadLine());
Exc obj = new Exc(n1, n2);
obj.Div(n1,n2);
Console.ReadKey();
}
Arithmetic operations with the float and double types never throw an exception. The result of arithmetic operations with those types can be one of special values that represent infinity and not-a-number:
double a = 1.0 / 0.0;
Console.WriteLine(a); // output: Infinity
Console.WriteLine(double.IsInfinity(a)); // output: True
Source
You are going to get divide by zero error only in case of integer input in c#. For double the desired output is infinity. You should put a check for Double.IsInfinity if you want to know if it is divided by zero.

Getting a CS7036 error when passing variables between methods for a calculator (from a code test I found on the internet))

CS7036 C# There is no argument given that corresponds to the required formal parameter 'num1' of 'Calculator.Add(int, int, int)' same error for subtracting, divide and multiply.
The test rules said that it must have separate methods for each operation.
Trying to get back into coding after taking an unavoidably long break. Thought tests would be a good way to spark the code brain again.
Anyway,
I've tried different method parameters, such as passing the variables as references and as straight values, different ways of calling the methods, different security parameters (private, public, static etc).
I've spent 2 hours trawling different forums and scripting references to see if there was anything, but so far no luck. The test rules said that it must have separate methods for each operation.
I had an earlier error about the num1 2 and op being passed without identifiers as well, so that may be contributing here.
I do know this isn't the most effective or efficient way to make a calculator, however, it is how the test wants it to be done.
using System;
namespace code_challenge.Challenges
{
public class Calculator
{
/*
* Within this Calculator class you will need to create 4 methods.
* The four methods will relate to the basic functions of a calculator
and should be named:
*
* - Add
* - Subtract
* - Multiply
* - Divide
int num1 =0; int num2 =0; int ans =0; string op = " ";
public void Input(int num1,int num2,int ans,string op)
{
Console.WriteLine("Please enter the first number.");
num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the opperand.");
op = Console.ReadLine();
Console.WriteLine("Please enter the Second number.");
num2 = Convert.ToInt32(Console.ReadLine());
if (op == "+")
{
ERROR LINE Add();
}
if (op == "-")
{
ERROR LINE Sub();
}
if (op == "*")
{
ERROR LINE Mul();
}
if (op == "/")
{
ERROR LINE Div();
}
}
// Implement the add function below here
public void Add(int num1, int num2, int ans)
{
ans = num1 + num2;
Console.WriteLine("Your Answer is: " + ans);
}
// Implement the subtract function below here
public void Sub(int num1,int num2,int ans)
{
ans = num1 - num2;
Console.WriteLine("Your Answer is: " + ans);
}
// Implement the multiply function below here
public void Mul(int num1,int num2,int ans)
{
ans = num1 * num2;
Console.WriteLine("Your Answer is: " + ans);
}
// Implement the divide function below here
public void Div(int num1,int num2,int ans)
{
ans = num1 / num2;
Console.WriteLine("Your Answer is: " + ans);
}
}
}
No actual output due to the errors.
The expected output is that the operand input will throw the if statement, which will throw the appropriate operation and push ans into the console
I'll help you with Add op and you repeat this with other methods:
first,
if (op == "+")
{
Add(num1, num2);
}
second, change add method
public void Add(int num1, int num2)
{
ans = num1 + num2;
Console.WriteLine($"Your Answer is: {num1 + num2}");
}
Firstly, you are not passing any input arguments to the function. You should provide that.
Secondly, you do not need to have an input argument called ans in any of the function.
You can modify your function as following
public void Add(int num1,int num2){
int ans = num1+num2;
Console.WriteLine(ans);
}
Or you can return the value from the method for example:
public int Add(int num1,int num2){
int ans = num1+num2;
Console.WriteLine(ans);
return ans;
}
and in the input method, pass
Add(num1,num2)

Overload Method Error with Switch statement

The application shall perform the selected menu math operation on the two entered numbers and display the answer.You must use methods for each math operation and a decision must be used to pick which method should be executed.
The application shall display an error message when a correct menu number is not entered. This is a decision where 1-5 are valid selections and everything else is “Invalid”.
The application shall not allow division by zero. Do not perform the divide operation if the second number variable is zero, but instead display an error message.
I have written the code but the program is showing the following error:
1. No overload for method AddNumber takes 0 arguments. this error is showing for all math operation methods inside the switch statements.
2. For DivideNumber method - not all code paths return a value
class Program
{
static void Main(string[] args)
{
double n1 = Convert.ToDouble(Console.ReadLine());
//string n2 = "";
double n2 = Convert.ToDouble(Console.ReadLine());
Console.Clear();
Console.WriteLine("Simple Calculator");
Console.WriteLine("\t 1) ADD");
Console.WriteLine("\t 2) SUBTRACT");
Console.WriteLine("\t 3) MULTIPLY");
Console.WriteLine("\t 4) DIVIDE");
Console.WriteLine("\t 5) QUIT");
Console.Write("Enter Selection: ");
int menuSelection =0;
// double total;
// menuSelection = Console.ReadLine();
switch (menuSelection)
{
case 1:
// total = Convert.ToInt32(AddNumbers("Results:"));
Console.WriteLine(AddNumbers(n1,n2));
break;
case 2:
Console.WriteLine(SubtractNumber(n1,n2));
break;
case 3:
Console.WriteLine(MultiplyNumber(n1,n2));
break;
case 4:
Console.WriteLine(DivideNumber(n1,n2));
break;
case 5:
break;
default:
Console.WriteLine("Invalid Selection !");
Console.ReadLine();
return;
}
//Ask user to enter two numbers
Console.WriteLine();
Console.Write("Enter Number 1:", n1);
// number1 = Console.ReadLine();
Console.Write("Enter Number 2:", n2);
// number2 = Console.ReadLine();
}
public static double AddNumbers(double number1, double number2)
{
return number1 + number2;
}
public static double SubtractNumber(double number1, double number2)
{
return number1 - number2;
}
public static double MultiplyNumber(double number1, double number2)
{
return number1 * number2;
}
public static double DivideNumber(double number1, double number2)
{
if (number1 == 0 && number2 == 0)
{
Console.WriteLine("Cannot Divide by Zero. Try Again");
return 0;
}
else
{
return number1 / number2;
}
}
1st mistake You are taking input after calling switch cases
2nd mistake your function have two parameters so pass them.
like DivideNumber(number1,number2) in your switch case
hope you understand
one thing i notice is you are taking input in string and your function takes double parameters so you need to convert string to double.
Give you idea use double to take input like double n1 = Convert.ToDouble(console.readline()); as input from console is string.
you are calling your function return AddNumbers();
but have declared it as public static double AddNumbers(double number1, double number2)
AddNumbers expected 2 numbers, you have passed 0.
You don't return anything from DivideNumbers, though you have declared it to return a double. public static double DivideNumber
The program makes no sense as it is. You are trying to do the operation before they've even given you the numbers. You should try to Rubber Duck this one yourself
This should do what your trying to accomplish.

Using variables in multiple methods

I am trying to use my three variables (num1, num2 and oper) in each of my methods but I can't find a way to do this anywhere in my book or on the internet. I realize there is much to be done before my program is ready and I will get it cleaned up as I learn. Right now I just need to know the code for importing the variables to different methods, I don't need the code fixed or improved. I hope this makes sense, I'm very new to this so forgive my ignorance and bear with me. Thank you very much for reading!
public class SimpleCalc
{
public double SimpleCalc(double num1, double num2, string oper)
{
Console.Write("Enter first integer: ");
num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter operator (+,-,*, / or %)");
oper = Convert.ToString(Console.ReadLine());
Console.Write("Enter second integer: ");
num2 = Convert.ToDouble(Console.ReadLine());
if (oper == "+");
return addNumbers();
if (oper == "-");
return subtractNumbers();
if (oper == "*");
return multiplyNumbers;
if (oper == "/");
return divideNumbers;
}
public double addNumbers()
{
Console.Write("The answer is: ", num1 + num2);
}
public double subtractNumbers()
{
Console.Write("The answer is: ", num1 - num2);
}
public double multiplyNumbers()
{
Console.Write("The answer is: ", num1 * num2);
}
public double divideNumbers()
{
Console.Write("The answer is: ", num1 / num2);
}
}
The easiest way it to simply declare them as parameters:
public double addNumbers(double num1, double num2)
{
return num1 + num2;
}
public double subtractNumbers(double num1, double num2)
{
return num1 - num2;
}
public double multiplyNumbers(double num1, double num2)
{
return num1 * num2;
}
public double divideNumbers(double num1, double num2)
{
return num1 / num2;
}
And pass the parameters to the other functions like this:
if (oper == "+")
return addNumbers(num1, num2);
if (oper == "-")
return subtractNumbers(num1, num2);
if (oper == "*")
return multiplyNumbers(num1, num2);
if (oper == "/")
return divideNumbers(num1, num2);
Note that I've modified your methods because they need to return a value. I've also modified the if statements because you had a semi-colon after each condition, which actually results in an empty conditional, followed by an immediate, unconditional return.
However, if you really need to store state variables within your class and reuse them in multiple methods, you should use fields or properties (which are usually backed by fields).

Categories

Resources