在if语句中增加变量

时间:2016-03-06 11:07:18

标签: java counter increment

以下是一段代码(else子句):

else { // for operators
            int count = 1;
            if (sub.compareTo("+") == 0){ //if + operator
                double d1=stack.pop();
                double d2=stack.pop();
                answer=d1+d2;
               //first two items on stack added
                stack.put(answer); // put ans on stack
               System.out.println(count+ ") "+d1+ " + " +d2 + " = " +answer); // display ans
               count++;
            }
            if (sub.compareTo("-") == 0){ //if - operator
                double d1=stack.pop(); //pop first two items on stack
                double d2=stack.pop();
                answer =d2-d1; //subtract the items
                stack.put(answer);//put ans on stack
                System.out.println(count+ ") "+d2+ " - " +d1 + " = " +answer);///display answer
                count++;
            }
}

此代码尝试使用stack评估基本数学运算。例如:

  1. 2 + 2 = 4
  2. 4 + 4 = 8
  3. 我想使用count变量来显示数字,但它保持为1.你知道为什么吗?

1 个答案:

答案 0 :(得分:1)

制作你的计数全局变量并在函数外声明它以正确存储值,你正在做的是限制计数的范围,这就是他每次都给你相同答案的原因

int count=1;  // make sure you count is outside your function 
else{ // for operators

            if(sub.compareTo("+")==0){ //if + operator
                double d1=stack.pop();
                double d2=stack.pop();
                answer=d1+d2;
               //first two items on stack added
                stack.put(answer); // put ans on stack
               System.out.println(count+ ") "+d1+ " + " +d2 + " = " +answer); // display ans
               count++;
            }
            if(sub.compareTo("-")==0){ //if - operator
                double d1=stack.pop(); //pop first two items on stack
                double d2=stack.pop();
                answer =d2-d1; //subtract the items
                stack.put(answer);//put ans on stack
                System.out.println(count+ ") "+d2+ " - " +d1 + " = " +answer);///display answer
                count++;
            }