【问题标题】:Index Out Of Bound Exception Error索引越界异常错误
【发布时间】:2017-03-23 22:22:59
【问题描述】:

几个小时以来,我一直在努力尝试修复此错误,但我无法弄清楚导致错误的位置/原因 (java.lang.IndexOutOfBoundsException: index:68 size: 26)

这会创建全部大写的字母表

String [] myStringsChars= new String[26];
        for(int i = 0; i < 26; i++)
        {
            myStringsChars[i] = new String(Character.toChars(i+65));
            System.out.println(myStringsChars[i]);

        }

我怀疑问题的原因是这两个循环之一

将数组字母添加到链表并将其设置为节点

int j=0;
    while (j<myStringsChars.length){

        BinaryTree.add(alphabet = new TreeNode(myStringsChars[j]));
        if (j<=26){
            j++;
        }
    }

设置节点父子节点

    int k =0;

    while (k<BinaryTree.size()){
        int find=(k-1)/2;
        BinaryTree.get(k).setParent(BinaryTree.get(find));

        if(k%2 ==0){
            (BinaryTree.get(k).getParent()). setRightChild(BinaryTree.get(k));
        }
        else{
            (BinaryTree.get(k).getParent()).setLeftChild(BinaryTree.get(k));
        }
        k++;
    }

这是我的其余代码以防万一

import java.util.*;

public class TreeExercise
{

    public static void main(String args[])
    {


        String [] myStringsChars= new String[26];
        for(int i = 0; i < 26; i++)
        {
            myStringsChars[i] = new String(Character.toChars(i+65));
            System.out.println(myStringsChars[i]);

        }
        List<TreeNode> BinaryTree = new LinkedList();

        int j=0;
        while (j<myStringsChars.length){

            BinaryTree.add(alphabet = new TreeNode(myStringsChars[j]));
            if (j<=26){
                j++;
            }
        }
        int k =0;

        while (k<BinaryTree.size()){
            int find=(k-1)/2;
            BinaryTree.get(k).setParent(BinaryTree.get(find));

            if(k%2 ==0){
                (BinaryTree.get(k).getParent()). setRightChild(BinaryTree.get(k));
            }
            else{
                (BinaryTree.get(k).getParent()).setLeftChild(BinaryTree.get(k));
            }
            k++;
        }
        BinaryTree.get(0).setParent(null);



        Scanner input= new Scanner(System.in);
        String userChoice="";
        while (!(userChoice.equals("end"))){
            System.out.println("enter two CAPITAL letters to find their common ancestor ex.(DC)\n type 'end' to end program");
            userChoice= input.nextLine();
            char letter1=userChoice.charAt(0);
            char letter2=userChoice.charAt(1);
            int let1= (int)letter1;
            int let2= (int)letter2;
            if(userChoice.length()<=2){
                // cant find BinaryTree ERROR

                TreeNode commonAncestor= findLowestCommonAncestor(root, BinaryTree.get(let1), BinaryTree.get(let2));
                if (commonAncestor !=null){
                    System.out.println(commonAncestor.getContents());
                    }
                System.out.println("Result is: " + "D");
            }
            else if (userChoice.equals("end")){
                System.exit(0);
            }
            else{
                System.out.println("you must type in 2 capital letters");
                userChoice=input.nextLine();
            }
        }
    }   

    public static TreeNode findLowestCommonAncestor(TreeNode root, TreeNode node1, TreeNode node2)
    {
findLowestCommonAncestor(root.getRightChild(), node1, node2)
        //every time
        TreeNode rightChild= findLowestCommonAncestor(root.getRightChild(), node1, node2);
        TreeNode leftChild= findLowestCommonAncestor(root.getLeftChild(), node1, node2);
        if (leftChild != null && rightChild!=null){
            return root;
        }
        if(root==null){
            return null;
        }


        if (leftChild!=null){
            return leftChild;
        }
        if(root.getContents()==node1 || root.getContents()==node2){
            return root;
        }

        else {
            return rightChild;
        }

    }       
}

TreeNode 节点

public class TreeNode<T extends Comparable>{
    private T contents;
    private TreeNode<T> parent;
    private TreeNode<T> leftChild;
    private TreeNode<T> rightChild;
    private int level;

    public TreeNode()
    {
        //added
        //parent=null;
        //leftChild=null;
        //rightChild=null;
        //level=0;
    }
    public TreeNode(T data){
    contents=data;
    this.parent=parent;
}

    public TreeNode(T data, TreeNode parent)
    {
        contents = data;
        this.parent = parent;
    }        

    public void setLeftChild(TreeNode node)
    {
        this.leftChild = node;
    }        

    public void setRightChild(TreeNode node)
    {
        this.rightChild = node;
    }        

    public boolean isContentEquals(T data)
    {
        return 0 == getContents().compareTo(data);
    }

    /**
     * @return the contents
     */
    public T getContents() {
        return contents;
    }

    /**
     * @param contents the contents to set
     */
    public void setContents(T contents) {
        this.contents = contents;
    }

    /**
     * @return the parent
     */
    public TreeNode getParent() {
        return parent;
    }

    /**
     * @param parent the parent to set
     */
    public void setParent(TreeNode parent) {
        this.parent = parent;
    }

    /**
     * @return the leftChild
     */
    public TreeNode getLeftChild() {
        return leftChild;
    }

    /**
     * @return the rightChild
     */
    public TreeNode getRightChild() {
        return rightChild;
    }
     /**
     * Given an object T contentToSearch, this method returns
     * the node that stores the contentToShare or null if not found on the current tree
     * @return the node
     */
    public TreeNode findNodeOnTree(T contentToSearch)
    {
        List<TreeNode> nodes = new LinkedList();
        nodes.clear();
        nodes.add(this);

        while(!nodes.isEmpty())
        {
            TreeNode current = nodes.remove(0);
            if(current.isContentEquals(contentToSearch))
            {
                return current;
            }

            if(current.leftChild != null)
            {
                nodes.add(current.leftChild);
            }   

            if(current.rightChild != null)
            {
                nodes.add(current.rightChild);
            }    
        }

        return null;
    }        

    /**
     * @return the level
     */
    public int getLevel() {
        return level;
    }

    /**
     * @param level the level to set
     */
    public void setLevel(int level) {
        this.level = level;
    }

}

【问题讨论】:

  • 请发布异常的完整堆栈跟踪,并指出您的代码的哪一行是堆栈跟踪中报告的那一行。
  • 您需要调试它以缩小原因。
  • java.lang.IndexOutOfBoundsException:索引:68,大小:26 在 java.util.LinkedList.checkElementIndex(LinkedList.java:555) 在 java.util.LinkedList.get(LinkedList.java:476 ) 在 TreeExercise.main(TreeExercise.java:113) 这是完整的错误消息,我现在正在查看它。 TreeNode commonAncestor= findLowestCommonAncestor(root, BinaryTree.get(let1), BinaryTree.get(let2));它说这是错误行,但似乎不是根本原因
  • 不要在评论中发布堆栈跟踪。编辑问题并将其添加到那里,然后删除该评论。 --- 另外,您说“我怀疑问题的原因是这两个循环之一”。当堆栈跟踪告诉您确切错误在哪里时,您是否会怀疑并且不知道,即TreeExercise.java 的第113行(这似乎很奇怪,因为您发布的TreeExercise源没有有那么多行)

标签: java exception indexing


【解决方案1】:

您的错误似乎在这里,猜测这是行TreeExercise.java:113

int let1= (int)letter1;
int let2= (int)letter2;
if(userChoice.length()<=2){
    // cant find BinaryTree ERROR
    TreeNode commonAncestor= findLowestCommonAncestor(root,
                        BinaryTree.get(let1), BinaryTree.get(let2));
                                       ^^^^                  ^^^^

您的树列表索引从 0 到 25,但 let1let2,给定输入 DE,是 6869。所以,试试:

int let1= (int)letter1 - 'A';
int let2= (int)letter2 - 'A';

在您的其他代码中使用'A' 而不是65 也会更清楚。

【讨论】:

  • 修复了错误,但是当尝试执行 findLowestCommonAncestor 方法时,当然会弹出一个新错误。 “TreeNode rightChild= findLowestCommonAncestor(root.getRightChild(), node1, node2);”行出现空指针异常错误
  • root == null 的检查移到findLowestCommonAncestor() 的开头。请自行继续调试,如果卡住了,请发新问题。
  • 接受肯的回答将是一个很酷的姿态......他得到了积分!
  • 啊,对不起,我刚开始使用这个网站。我刚刚投了赞成票。
猜你喜欢
  • 1970-01-01
  • 2015-06-13
  • 1970-01-01
  • 2018-11-19
  • 2013-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-30
相关资源
最近更新 更多