java - 数组索引越界错误

标签 java

我编写的这段代码遇到了一些问题,因为我收到了 ArrayIndexOutofBounds 异常错误,而且我不知道发生了什么。我希望我的代码生成的是数字的 char 数组。

代码如下:

public class testing {

    static int k = 2;

    public static void main(String args[]) {

        int[] numArr = new int[] { 15, 18, 21 };

        createChar(numArr, k);
    }

    public static char[] createChar(int numArr[], int k) {
        char[] store = new char[k - 1];

        for (int i = 0; i < k; i++) {
            int divide = numArr[i] / 4;

            int numStore = divide % 4;
            charN(numStore, store, k);
        }
        return store;
    }

    public static char[] charN(int numStore, char store[], int k) {
        for (int i = 0; i < k; i++) {
            if (k == 0) {
            } else {
                store[k - 1] = (char) numStore;
                k = k - 1;
            }
        }
        System.out.print(store);
        return store;
    }
}

非常感谢!

最佳答案

正如错误所示,这是由于访问超出了数组范围。 IE。数组上的一些错误索引访问。

char[] store = new char[k - 1];

您正在创建一个大小为 k-1store字符数组

并将 k 作为大小传递给 charN()

charN(numStore, store, k);

解决您的问题。 更改商店声明如下

char[] store = new char[k];

此外,在类测试中,k必须为3,而不是2。其中k是数组的大小。

static int k = 3;

当数组的大小为k时,数组的索引0k-1

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

相关文章:

java - 如何使用 StringTokenizer 将字符串存储到 HashMap 中

java - 如何创建单例 OkHtpp 类并处理以前的请求

java - Swing - 确保文本组件中的可见行

Java 从 UTF-8 格式的 URL 读取 XML?

java - Eclipse 中的 Hibernate 工具 : Change in column values does not reflecting in the query result

java - CellList 空小部件和 AsyncDataProvider 出现问题

java - 使用 java jdbc 和准备好的语句创建数据库查询返回语法错误

java - 从文本文件中检测数组

java - Selenium 循环发送 key

java - :_* do when calling a Java vararg method from Scala? 是什么意思