java - 索引越界异常错误

标签 java exception indexing

我已经花了几个小时尝试修复此错误,但我无法弄清楚导致错误的位置/原因 (java.lang.IndexOutOfBoundsException:索引:68 大小: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;
    }

}

最佳答案

您的错误似乎就在这里,猜测这是行 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,但在给定输入 DE 的情况下,let1let2 的索引为 68 69。所以,尝试:

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

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

关于java - 索引越界异常错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40518308/

相关文章:

python - FileNotFoundError "try .. except IOError"未捕获时如何处理?

python - 自定义 python 生成器中的 Return 和 StopIteration

pandas - 使用基于其他列 pandas 中的值的拆分和索引来处理一列中的数据

python - 字符串中子字符串的基本索引重复(python)

java |上一帧没有消失

java - JUnit 4.8 需要什么 java 版本

python - 重试代码时很好的异常处理

mysql - 在 mysql 中执行带索引和不带索引的查询

适用于 Windows VHD API 的 Java 库

java - 配置Spring Bean以重用其自己的属性?