Java 用负数计算后修复
我很难想出如何让我的后缀计算负数 我的中缀到后缀似乎可以很好地处理负数,比如我的程序中的例子。。 中缀:(-3)+5*3 后缀:3-53*+Java 用负数计算后修复,java,stack,postfix-notation,Java,Stack,Postfix Notation,我很难想出如何让我的后缀计算负数 我的中缀到后缀似乎可以很好地处理负数,比如我的程序中的例子。。 中缀:(-3)+5*3 后缀:3-53*+ EVAUATION push 3 read - ---> you have no 2 elements in the stack -> EXCEPTION (or by luck you can have 2 but is not the behavior you want) 这是我的评估方法,我知道代码越少越好,如果你想看到我的其他代码
EVAUATION
push 3
read - ---> you have no 2 elements in the stack -> EXCEPTION
(or by luck you can have 2 but is not the behavior you want)
这是我的评估方法,我知道代码越少越好,如果你想看到我的其他代码,请告诉我。我已经尝试了很多事情,但没有运气,任何建议或建议将不胜感激
public int evaluate(String evalute){
int number1;
int number2;
int result = 0;
int finalResult = 0;
Stack<Integer> d = new Stack<Integer>();
for(int i = 0; i < evalute.length(); i++){
char curChar = evalute.charAt(i);
if(curChar >= 48 && curChar <= 57){
int store = curChar;
store -=48;
d.push(store);
}
else if(curChar == '+'){
number1 = d.pop();
number2 = d.pop();
result = number1 + number2;
d.push(result);
}
else if(curChar == '-'){
number1 = d.pop();
number2 = d.pop();
result = number2 - number1;
d.push(result);
}
else if(curChar =='*'){
number1 = d.pop();
number2 = d.pop();
System.out.println(result = number1 * number2);
d.push(result);
}
else if(curChar =='/'){
number1 = d.pop();
number2 = d.pop();
result = number2 / number1;
d.push(result);
}
}
finalResult = d.pop();
return finalResult;
}
public int evaluate(字符串evalute){
整数1;
整数2;
int结果=0;
int finalResult=0;
堆栈d=新堆栈();
对于(int i=0;i=48&&curChar我就以你为例
中缀:(-3)+5*3后缀:3-53*+
EVAUATION
push 3
read - ---> you have no 2 elements in the stack -> EXCEPTION
(or by luck you can have 2 but is not the behavior you want)
到目前为止似乎一切正常,但是..如何区分一元负号和二元负号?当你读3-3时,你读的是两个操作数的减法运算还是两个原始操作数的负号
最容易采用的解决方案是使用不同的符号来标记负数,如字母!
或与减号本身不同的任何符号,否则在读取减号时,从堆栈中弹出两个元素并执行减法
相反,你想要读一个符号,比如!
,你弹出一个元素(d
),然后把它推回堆栈-d
所以从(-3)+5*3后缀:3!53*+
EVALUATION
push 3
read ! --> pop 3 and push -3
push 5 - push 3
read * ---> pop 5 - pop 3 push 3*5
read + ---> pop 15 (= 3*5) pop -3 and push 15 + (-)3
通过使用这两个不同的符号,您已经解决了您的问题。我想这是在解析字符串阶段。
您的解析器应该检测它是负数还是正数,生成标记后,您可以继续将中缀转换为后缀并计算后缀。我希望这会有所帮助:)添加一些详细信息,可能是一个代码块来澄清您的答案。