【问题标题】:StringIndexOutOfBoundsException in PrefixtoPostFix Stack (Java)PrefixtoPostFix 堆栈中的 StringIndexOutOfBoundsException (Java)
【发布时间】:2019-09-21 11:09:25
【问题描述】:

这个项目有两个类。 Main 方法是 Test2,子类是 Stack。这里的错误部分是这部分:

栈 s = 新栈(20);

每当我运行它时,它的输出是这样的:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
    at java.lang.String.charAt(Unknown Source)
    at com.stack.Test2.prefixToPostfix(Test2.java:31)
    at com.stack.Test2.main(Test2.java:18)

如果 Stack 泛型一直响应错误,我应该如何放置“n 个项目”?

下面的主要方法:

 package com.stack;
        import java.util.Stack;
        //PREFIX TO POSTFIX
        public class Test2 {
            public static void main(String[] args) {
                String prefix1 = "A + B * C";
                System.out.println(prefixToPostfix(prefix1));
            }

    static String prefixToPostfix(String prefix) {
        Stack<String> s = new Stack(100); 
        String[] tokens = prefix.split(" ");
        for (int i = tokens.length-1; i>=0; i--) {
            String token = tokens[i];
            if (Character.isLetterOrDigit(token.charAt(i))) { 
                String op1 = s.peek(); s.pop();
                String op2 = s.peek(); s.pop();
                String exp = op1 + op2 + token;
                s.push(exp); 
            } 
            else {
                s.push(token + " "); 
            } 
        } 
        return s.peek(); 
    } 
}

这是 ISEMPTY、ISFULL、PEEK、PUSH 等的堆栈操作。

package com.stack;
public class Stack<T> {  
    int size;
    T A[];
    int top = -1;

    public Stack(int size) {
        this.size = size;
        A = (T[]) new Object[size];
        top = -1;
    }
    public void push(T item) {
        top++;
        A[top] = item;
    }

    public void pop() {
        top--;
    }

    public boolean isEmpty() { 
        if(top == - 1) {
            return true;
        }
        return false;
    }
    public T peek() {
        return A[top];
    }
}

【问题讨论】:

    标签: java stack postfix-mta prefix stringindexoutofbounds


    【解决方案1】:

    替换这个

     if (Character.isLetterOrDigit(token.charAt(i))) 
    

    有了这个

      if (Character.isLetterOrDigit(token.charAt(0)))
    

    您收到此错误是因为令牌数组中每个变量的长度为 1,并且您试图在第 4 个位置获取字符。

    【讨论】:

      猜你喜欢
      • 2013-07-06
      • 1970-01-01
      • 2011-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-16
      • 2012-02-06
      • 1970-01-01
      相关资源
      最近更新 更多