Reputation: 59
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);
}
}
Upvotes: 0
Views: 1744
Reputation: 149068
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).
Upvotes: 2