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).
Related
I'm trying to make simple projects for learning C# and have tried to make a simple console calculator. I have only found this current error when getting to the getting/printing the answer bit when test-running my program, so I have no idea if there are any other errors/things that will or may not work or run properly/as intended. So if there are any of those, please let me know and if you want to you can fix them yourself. It only recognized the error when it reached that specific line of code, and otherwise will run the program until it reaches the error.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Calculator
{
class Program
{
static void Main(string[] args)
{
string num1;
string num2;
string condition;
string answer;
Console.WriteLine("Calculator");
Console.WriteLine("For division, use /. For multiplication, use *.\n");
while (true)
{
Console.WriteLine("Enter a number: "); // gets first number to add in problem
num1 = Console.ReadLine();
Console.WriteLine("Enter a condition: "); // gets condition to add in problem
condition = Console.ReadLine();
Console.WriteLine("Enter your second number: "); // gets second number to add in problem
num2 = Console.ReadLine();
Console.WriteLine("Calculating..");
// converting strings to int and working out answer
Convert.ToInt32(num1);
Convert.ToInt32(num2);
// error is from here on (not sure if the Convert.ToInt32() code above causes errors)
answer = num1 + condition + num2;
Convert.ToInt32(answer);
Console.WriteLine(answer);
// sets values to null after getting & printing answer (probably unnessessary)
answer = null;
num1 = null;
num2 = null;
condition = null;
}
}
}
}
When facing problems like this one - the routine is too complex to be tested:
if there are any other errors/things that will or may not work"
split routine into smaller ones: start extracting methods.
// Get integer value from user
public static int ReadInteger(string title) {
while (true) {
if (!string.IsNullOrEmpty(title))
Console.WriteLine(title);
if (int.TryParse(Console.ReadLine(), out int result))
return result;
Console.WriteLine("Sorry, not a valid integer value, please, try again.");
}
}
// Get character operator ('+', '-' etc.) from user
public static char ReadOperator(string title, string operators) {
while (true) {
if (!string.IsNullOrEmpty(title))
Console.WriteLine(title);
string input = Console.ReadLine().Trim();
if (input.Length == 1 && operators.Contains(input[0]))
return input[0];
Console.WriteLine("Sorry, not a valid operator, please, try again.");
}
}
Now we are ready to implement Main method:
static void Main(string[] args) {
while (true) {
int num1 = ReadInteger("Enter a number: ");
char op = ReadOperator("Enter a condition: ", "+-*/");
int num2 = ReadInteger("Enter your second number: ");
//TODO: I've skipped error handling (zero division, overflow)
int answer =
op == '+' ? num1 + num2 :
op == '-' ? num1 - num2 :
op == '*' ? num1 * num2 :
op == '/' ? num1 / num2 : 0;
Console.WriteLine($"{num1} {op} {num2} = {answer}");
//TODO: it's a right place here to ask user if (s)he wants to continue
Console.WriteLine();
}
}
You receive input (condition) as a string
cant do this : answer = num1 + condition + num2 because those variables are
string
you have to check that with switch , for example :
int num1 = 0, num2 = 0, answer = 0;
string condition;
Console.WriteLine("Calculator");
Console.WriteLine("For division, use /. For multiplication, use *.\n");
while (true)
{
Console.WriteLine("Enter a number: "); // gets first number to add in problem
num1 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter a condition: "); // gets condition to add in problem
condition = Console.ReadLine();
Console.WriteLine("Enter your second number: "); // gets second number to add in problem
num2 = int.Parse(Console.ReadLine());
Console.WriteLine("Calculating..");
// converting strings to int and working out answer
Convert.ToInt32(num1);
Convert.ToInt32(num2);
// error is from here on (not sure if the Convert.ToInt32() code above causes errors)
switch (condition)
{
case "/":
answer = num1 / num2;
break;
case "*":
answer = num1 * num2;
break;
case "+":
answer = num1 + num2;
break;
case "-":
answer = num1 - num2;
break;
default:
Console.WriteLine("error : unknown operator");
break;
}
Console.WriteLine(answer);
// sets values to null after getting & printing answer (probably unnessessary)
}
You can't do this line because all the variables are strings and not the real values (e.g: num1 & num2 should ints/doubles... and condition should be a real operator).
answer = num1 + condition + num2;
Also, you can't do it because let's assume the user inputs the multiplication sign, and then the string of "*" is not equal to the sign of *.
Instead, you can do some switch-case statements to check the value of the condition variable. Also, you need to make sure num1 & num2 are numbers (you can parse/try-parse them to a number (int/double...)). You will also have to parse them to another variables as they are strings.
switch (condition)
{
case '*':
answer = numX * numY;
break;
case "/":
// Validate that numY is not 0 to avoid [DivideByZeroException][1]
answer = numX / numY;
break;
...
}
Note, it is just one way to do it and I just gave you a small example that might help you to continue.
I would also offer you to make a default case (in case that the input of the user is not something you expect, in this case, you may ask him again to write an input because the current input is invalid).
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);
}
}
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)
I'm still in the middle of my programming assignment trying to use methods to make a calculator, and I am getting:
Member 'LabAssignFiveCalc.Sum.Addition(double, double)' cannot be accessed with an instance reference; qualify it with a type name instead
on this line of code
Sum s = new Sum();
if (metUse == "Addition")
result = s.Addition(num1, num2);
Here's the entire file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LabAssignFiveCalc
{
public class Sum
{
//Addition method
public static double Addition(double num1, double num2)
{
double result;
result = num1 + num2;
return result;
}
//Subtraction method
public static double Subtract(double num1, double num2)
{
double result;
result = num1 - num2;
return result;
}
//Multiplication method
public static double Multiply(double num1, double num2)
{
double result;
result = num1 * num2;
return result;
}
//Division method
public static double Divide(double num1, double num2)
{
double result;
result = num1 / num2;
return result;
}
}
public class Program
{
//Main
static void Main(string[] args)
{
//Declare Variables
int choice;
string op;
double num1;
double num2;
double result;
string metUse;
//Ask user for calculation parameters
Console.WriteLine("Calculator:");
Console.WriteLine("Which operation do you wish to perform? Type the corresponding number.");
Console.WriteLine("1) Addition\n2) Subration\n3) Multiplication\n4) Division");
choice = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please type the first number you wish to calculate");
num1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Please type the second number you wish to calculate");
num2 = Convert.ToDouble(Console.ReadLine());
//Declare Operator
switch (choice)
{
case 1:
op = "+";
metUse = "Addition";
break;
case 2:
op = "-";
metUse = "Subtract";
break;
case 3:
op = "*";
metUse = "Multiply";
break;
case 4:
op = "/";
metUse = "Divide";
break;
default:
throw new ArgumentException();
}
Sum s = new Sum();
if (metUse == "Addition")
result = s.Addition(num1, num2);
//Show Calculation
Console.WriteLine("{0}{1}{2}={3}", num1, op, num2, result);
Console.ReadKey();
}
}
}
Like I said, I'm still a beginner so go easy on me please :P It's probably some really rookie error.
Thanks for the help :D
Addition is a static method.
You cannot call a static method using an instance of a type; call it with the type itself.
Try this instead:
if (metUse == "Addition")
result = Sum.Addition(num1, num2);
The Addition member of the Sum class is marked as static. This means it cannot be called on an instantiated class. Do this instead:
result = Sum.Addition(num1, num2);
As the addition is a static method in Sum class, then it can be accessed as sum.addition(a,b);
and you don't have to create an object to use it.
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.