Simple Calculator problem, not reading in answer [duplicate]
Possible Duplicate:
Making a simple calculator cannot exit loop or give answer
hi, so basically my code at the moment takes the l开发者_如何学编程ast value in and does the calculation with the same number so 5+6=12 how can i store the operands and then use them in the calculation
public double getResult(){
if (getOperator() == '+')
{
result = (getOperand() + getOperand());
}
if (getOperator() == '-')
{
result = (getOperand() - getOperand());
}
if (getOperator() == '*')
{
result = (getOperand() * getOperand());
}
if (getOperator() == '/')
{
result = (getOperand() / getOperand());
}
return result;
}
public boolean getanswer(String value)
{
boolean isnum = false;
try {
setOperand(Double.parseDouble(value));
operand = (Double.parseDouble(value));
getResult();
isnum = true;
}
catch(Exception e)
{
try {
setOperator(value.charAt(0));
operator = (value.charAt(0));
isnum = false;
}
catch(Exception e2)
{
System.out.println("Enter a number");
}
You may restructure your program as follows to get what you want:
- read first operand and save into variable operand1
- read operator and save into variable operator
- read second operand and save into variable operand
- perform calculation result = operand1 operator operand2
If you want to loop this one you can add another step: 5. replace operand1 with result and goto 2.
In your design to try to do this within a single calculator class. Since you do not have the "main" loop in there you somehow have to save the state you are currently in (i.e. something like the step number of the algorithm). This would result in something like:
- if i'm in state 1 and an operand is coming in: save in variable operand1 and update state variable to 2.
- if i'm in state 2 and an operator is coming in: save in variable operator and update state variable to 3.
...
精彩评论