我正在尝试编写一个将中缀转换为前缀的方法,并且我想要读取反向并使用堆栈。当我执行此代码时,我在 character = expression.charAt(limit);
处获得异常如何修复该代码?
我的输入是 1 + 3 ,我得到的错误是:
线程“main”中的异常java.lang.StringIndexOutOfBoundsException: 字符串索引超出范围:java.lang.String.charAt中的3(未知 来自)PrefixTranslator.translate(PrefixTranslator.java:27)at PrefixTranslatorTest.main(PrefixTranslatorTest.java:11)
PrefixTranslator类:
public class PrefixTranslator
{
static private String expression;
private MyStack<Character> stack = new MyStack<Character>();
//Constructor
public PrefixTranslator(String infixExpression)
{
expression = infixExpression;
}//End of constructor
public String translate()
{
//Declare Method Variables
String input = "";
String output = "";
char character = ' ';
char nextCharacter = ' ';
for(int limit = expression.length(); limit > 0 ; limit--)
{
character = expression.charAt(limit);
if(isOperator(character))
{
output = output + character + " ";
}
else if(character == '(')
{
stack.push(character);
}
else if(character == ')')
{
while(!stack.top().equals('('))
output = output + stack.pop() + " ";
stack.pop();
}
else
{
if(Character.isDigit(character) && (limit + 1) < limit && Character.isDigit(expression.charAt(limit+1)))
{
stack.push(character);
stack.push(expression.charAt(limit+1));
}
else if(Character.isDigit(character))
{
stack.push(character);
}
else
{
output = output + character;
}
}
}//End of for
while(!stack.isEmpty())
{
output = output + stack.pop() + " ";
}
return output;
}//End of translate method
//Check priority on characters
public static int precedence(char operator)
{
if(operator == '+' || operator =='-')
return 1;
else if(operator == '*' || operator == '/')
return 2;
else
return 0;
}//End of priority method
public boolean isOperator(char element)
{
if(element == '*' || element == '-' || element == '/' || element == '+')
return true;
else
return false;
}//End of isOperator method
}//End of class
PrefixTranslatorTest类:
import java.util.Scanner;
public class PrefixTranslatorTest{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the expression that you want to convert to prefix.");
String expression = input.next();
PrefixTranslator translator = new PrefixTranslator(expression);
System.out.println(translator.translate());
}
}
答案 0 :(得分:1)
Java数组的第一个索引是0
,方法length()
返回数组的元素数。如果您需要最后一个元素的索引,请使用
length() - 1
。
所以而不是
for (int limit = expression.length(); limit > 0; limit--)
使用
for (int limit = expression.length() - 1; limit >= 0; limit--)
答案 1 :(得分:1)
对于给定的输入1+3
expression.length()
返回3
,您可以引用该字符串的索引0-2
。所以,你的循环不应该是:
for(int limit = expression.length(); limit > 0 ; limit--)
它应该是
for(int limit = expression.length() - 1; limit >= 0 ; limit--)