我正在研究我的代码而且我已经陷入困境。 我的问题是评估从键盘输入的后缀表示法。
这是我的代码:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.NoSuchElementException;
interface Stack<E> {
// The elements of the Stack are any kind of objects
// Access methods:
public boolean isEmpty ();
// Returns true only if the stack is empty.
public E peek ();
// Returns the element on the top od the stack.
// Transformation methods:
public void clear ();
// Clears the stack.
public void push (E x);
// Adds x on the top of the stack.
public E pop ();
// Removes and returns the element on the top.
}
class ArrayStack<E> implements Stack<E> {
private E[] elems;
private int depth;
@SuppressWarnings("unchecked")
public ArrayStack (int maxDepth) {
// Creating new empty stack
elems = (E[]) new Object[maxDepth];
depth = 0;
}
public boolean isEmpty () {
// Returns true only if the stack is empty.
return (depth == 0);
}
public E peek () {
// Returns the element on the top od the stack.
if (depth == 0)
throw new NoSuchElementException();
return elems[depth-1];
}
public void clear () {
// Clears the stack.
for (int i = 0; i < depth; i++) elems[i] = null;
depth = 0;
}
public void push (E x) {
// Adds x on the top of the stack.
elems[depth++] = x;
}
public E pop () {
// Removes and returns the element on the top.
if (depth == 0)
throw new NoSuchElementException();
E topmost = elems[--depth];
elems[depth] = null;
return topmost;
}
}
public class PostFixEvaluation {
static int evaluatePostfix(char [] izraz, int n)
{
ArrayStack e;
char ch;
int op1,op2,result=0;
int i=0;
while(i<n)
{
if(Character.isDigit(izraz[i]))
{
ch=izraz[i];
e.push(ch);
}
else
{
ch=izraz[i];
op1 =(int)e.pop();
op2 =(int)e.pop();
if(ch=='+')
{
result=op1+op2;
}
if(ch=='-')
{
result=op1-op2;
}
if(ch=='/')
{
result=op1/op2;
}
if(ch=='*')
{
result=op1*op2;
}
e.push(result);
}
i++;
}
return result;
}
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String expression = br.readLine();
char exp[] = expression.toCharArray();
int rez = evaluatePostfix(exp, exp.length);
System.out.println(rez);
br.close();
}
}
我的问题在于evaluatePostfix函数。我无法使用推送和弹出功能,因为它给了我这个错误:
PostFixEvaluation.java:100:错误:变量e可能尚未初始化 e.push(CH); ^ PostFixEvaluation.java:105:错误:变量e可能尚未初始化 op1 =(int)e.pop(); ^ 注意:PostFixEvaluation.java使用未经检查或不安全的操作。
有人可以帮我解决这个问题吗?
static int evaluatePostfix(char [] izraz, int n)
{
ArrayStack e;
char ch;
int op1,op2,result=0;
int i=0;
while(i<n)
{
if(Character.isDigit(izraz[i]))
{
ch=izraz[i];
e.push(ch);
}
else
{
ch=izraz[i];
op1 =(int)e.pop();
op2 =(int)e.pop();
if(ch=='+')
{
result=op1+op2;
}
if(ch=='-')
{
result=op1-op2;
}
if(ch=='/')
{
result=op1/op2;
}
if(ch=='*')
{
result=op1*op2;
}
e.push(result);
}
i++;
}
return result;
}
答案 0 :(得分:0)
在函数e
evaluatePostfix
ArrayStack<Character> e = new ArrayStack(10); // maxDepth = 10