private class InputListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// Create an integer and character stack
Stack<Integer> operandStack = new Stack<Integer>();
Stack<Character> operatorStack = new Stack<Character>();
// User input in input text field
String input = inputTextField.getText();
// Create string tokenizer containing string input
StringTokenizer strToken = new StringTokenizer(input);
// Loop while there are tokens
while (strToken.hasMoreTokens())
{
String i = strToken.nextToken();
int operand;
char operator;
try
{
operand = Integer.parseInt(i);
operandStack.push(operand);
}
catch (NumberFormatException nfe)
{
operator = i.charAt(0);
operatorStack.push(operator);
}
}
// Loop until there is only one item left in the
// operandStack. This one item left is the result
while(operandStack.size() > 1)
{
// Perform the operations on the stack
// and push the result back onto the operandStack
operandStack.push(operate(operandStack.pop(),
operandStack.pop(), operatorStack.pop()));
}
// Display the result as a string in the result text field
resultTextField.setText(Integer.toString(operandStack.peek()));
}
// Sum and product computed
public int operate(Integer operand1, Integer operand2, char operator)
{
switch(operator)
{
case '*':
return operand2 * operand1;
case '/':
return operand2 / operand1;
case '%':
return operand2 % operand1;
case '+':
return operand2 + operand1;
case '-':
return operand2 - operand1;
default:
throw new IllegalStateException("Unknown operator " + operator + " ");
}
}
}
Предоставляемый код префикса неверно оценивает выражения с несколькими операторами. Выражение: * + 16 4 + 3 1
должно оцениваться до 80 = ((16 + 4) * (3 + 1))
, но вместо этого оно оценивается до 128
, что, по моему мнению, оценивается как: ((16 + 4) * (3 + 1) + (16 * 3))
. Как отредактировать код, чтобы исправить эту проблему? Спасибо за помощь.
При оценке префикса важно помнить, что важно помнить
операнд 1 = pop();
операнд 2 = pop();
и говорят, что оператор -
Выводимое значение - это операнд 1 - операнд 2, а не операнд 2 - операнд 1
Но что-то другое вызывает * + 16 4 + 3 1 для оценки до 128.
Я использовал следующий алгоритм для оценки в java, и он отлично работает
1.Вставьте префиксное выражение как строку в переменной с символами, разделенными одним пробелом.
2. Перетащите строку из длины индекса-1 в 0
3.Если его число, выполните push, и если его многозначный номер, сначала получите полное число, а затем нажмите его
4. Если его оператор просто сделает то, о чем я упомянул в начале ответа.
Это простой код.
import java.io.*;
import java.util.*;
class PREFIXEVAL
{
public static void main(String []args)throws IOException
{
String p,n="";StringBuffer b;int i,op1,op2;char c;Stack<Integer> s=new Stack<Integer>();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the prefix expression separated by spaces");
p=br.readLine();
i=p.length()-1;
while(i>=0)
{
c=p.charAt(i);
if(c>=48&&c<=57)
n=n+c;
else if(c==' '&&!n.equals(""))
{/*handles both single and multidigit numbers*/
b=new StringBuffer(n);b.reverse();n=b.toString();
s.push(Integer.parseInt(n));n="";
}
else
{
if(c=='+')
{
op1=s.pop();
op2=s.pop();
s.push(op1+op2);
}
else if(c=='-')
{
op1=s.pop();
op2=s.pop();
s.push(op1-op2);
}
else if(c=='*')
{
op1=s.pop();
op2=s.pop();
s.push(op1*op2);
}
else if(c=='%')
{
op1=s.pop();
op2=s.pop();
s.push(op1%op2);
}
else if(c=='/')
{
op1=s.pop();
op2=s.pop();
s.push(op1/op2);
}
}
i--;
}
System.out.println("the prefix expression evaluates to "+s.peek());
}
}
operandStack
* + 16 4 + 3 1
,operatorStack
иoperandStack
вwhile(operandStack.size() > 1)
будут в том же состоянии, как если бы вы нажали* + + 16 4 3 1
, или16 4 3 1 * + +
.