以下是一段代码(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
评估基本数学运算。例如:
我想使用count
变量来显示数字,但它保持为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++;
}