开发者

Simple Calculator problem, not reading in answer [duplicate]

开发者 https://www.devze.com 2023-02-18 06:58 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Making a simple calculator cannot exit loop or give answer
This question already has answers here: Closed 11 years ago.

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:

  1. read first operand and save into variable operand1
  2. read operator and save into variable operator
  3. read second operand and save into variable operand
  4. 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.

...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号