Created
October 14, 2012 18:29
-
-
Save benfb/3889402 to your computer and use it in GitHub Desktop.
Calculator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//I accidentally switched up operand and operator, but the program has the same effect | |
public class Calculator | |
{ | |
//instance variables | |
private double num1; | |
private double num2; | |
private char operand; | |
//default constructor | |
public Calculator() | |
{ | |
num1 = 0; | |
num2 = 0; | |
operand = 0; | |
} | |
//inialization constructor | |
public Calculator(double n1, double n2, char op) | |
{ | |
num1 = n1; | |
num2 = n2; | |
operand = op; | |
} | |
//modifier method for num1 | |
public void setNum1(double n1) | |
{ | |
num1 = n1; | |
} | |
//modifider method for num2 | |
public void setNum2(double n2) | |
{ | |
num2 = n2; | |
} | |
//modifier method for operand | |
public void setOperand(char op) | |
{ | |
operand = op; | |
} | |
//accessor method for num1 | |
public double getNum1() | |
{ | |
return num1; | |
} | |
//accessor method for num2 | |
public double getNum2() | |
{ | |
return num2; | |
} | |
//accessor method for operand | |
public char getOp() | |
{ | |
return operand; | |
} | |
//Create method to calculate the result | |
public double calculate() | |
{ | |
double ans; //creates the double called ans | |
if(operand == '+'){ans = num1 + num2; return ans;} //if +, add and return ans | |
else if(operand == '-'){ans = num1 - num2; return ans;} //if -, subtract and return ans | |
else if(operand == '*'){ans = num1 * num2; return ans;} // if *, multiply and return ans | |
else if(operand == '/'){ans = num1 / num2; return ans;} // if /, divide and return ans | |
} | |
//Create the toString() method | |
public String toString() | |
{ | |
return "" + num1 + operand + num2 + " = " + calculate() ; //prints out number one, operand, two, equals, and ans as calculated by calculate() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment