每当我为我的项目编译此代码时,总是会出现错误。我正在尝试为我的编程课编写一个实际的计算器。当我编译它时,bluej说“它找不到符号-变量isOperator”。
import java.util.*;
public class InfixtoPostFix
{
// instance variables - replace the example below with your own
//insert nested class SyntaxErroeException.
public static class SyntaxErrorException extends Exception{
SyntaxErrorException (String message){
super(message);
}
}
//data fields
/**The operator Stack */
private Stack<Character> operatorStack;
/** THe operator */
private static final String OPERATORS = "+-*/";
/** The precedence of the operators mathces the order in Operators */
private static final int[] PRECENDENCE = {0,1,1,2,2,2};
/** Postfix string */
private StringBuilder postfix;
public String convert(String infix) throws SyntaxErrorException{
operatorStack = new Stack<Character>();
postfix = new StringBuilder();
String[] tokens = infix.split("\\s+");
//process each token in the infix string
try{
for(String nextToken : tokens){
char firstChar = nextToken.charAt(0);
//is it an operand
if(Character.isJavaIdentifierStart(firstChar) || Character.isDigit(firstChar)){
postfix.append(nextToken);
postfix.append(' ');
}else if(isOperator(firstChar)){
//is it an operator
processOpperator(firstChar);
}else{
throw new SyntaxErrorException("Unexpected Character Encountered: " + firstChar);
}
}
//pop any remaing opperators
//appen them to post fix
while(!operatorStack.empty()){
char op = operatorStack.pop();
postfix.append(op);
postfix.append(' ');
}
//assert =: stack is empty return result
return postfix.toString();
}catch(EmptyStackException e){
throw new SyntaxErrorException("Syntax error: The stack is empty");
}
}
private void processOpperator(char op){
if(operatorStack.empty()){
operatorStack.push(op);
}else{
//peek the operator stack and ler topOp be the top operator
char topOp = operatorStack.peek();
if(precedence(op) > precedence(topOp)){
operatorStack.push(op);
}else{
//pop all stacked operators with equal or higher prededence than op
while(!operatorStack.empty() && precedence(op) <= precedence(op)){
operatorStack.pop();
postfix.append(topOp);
postfix.append(' ');
if(!operatorStack.empty()){
topOp = operatorStack.peek();
}
}
//assert: operator stack is empty or current operator precedence > top of stack operator preceence
operatorStack.push(op);
}
}
}
private boolean isOperator(char ch){
return isOperator.indexOf(ch) != 1;
}
private int precedence(char op){
return PRECEDENCE[OPERATORS>indexOf(op)];
}
}
最佳答案
在方法isOperator
中,您编写:return isOperator.indexOf(ch) != 1;
,使用一个名为isOperator
的变量,但是我想您应该使用静态成员变量OPERATORS
;我想您应该将indexOf
的返回值与-1
而不是1
进行比较,如果要检查ch
是否在OPERATORS
中,请更改
private boolean isOperator(char ch){
return isOperator.indexOf(ch) != 1;
}
至
private boolean isOperator(char ch){
return OPERATORS.indexOf(ch) != -1;
}
关于java - 变量isOperator的编译错误是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23452870/