java - 数组越界异常,找不到问题所在

标签 java arrays

基本上,我在第 19 行遇到了 ArrayOutOfBounds 异常。我尝试只打印数组的内容而不分配任何值(注释掉 wile 循环),但仍然是相同的错误,有人有修复吗?

package com.company;

import java.util.Random;

public class Main {
    static int[][] Placer = new int[2][2]; //create multi-dimenstional array to hold the numbers

    public static void main(String[] args) {
        Random random = new Random(); //intiallise new Random object
        int intsAssigned = 0; //will keep track of the ammount of ints assigned.



        //Assign all of the index's a random int, not the most practical way.
        while(intsAssigned != 9){
            int currentColumn = 0;
            Placer[currentColumn][0] = random.nextInt(20);
            Placer[currentColumn][1] = random.nextInt(20);
            Placer[currentColumn][2] = random.nextInt(20);
            currentColumn++;
            intsAssigned + 3;

        }
        printNumbers();

    }

    //Print all of the index's
    public static void printNumbers(){
        int numbersPrinted = 0;
        int currentColumn = 0;
        int currentRow = 0;
        while(numbersPrinted != 9){
            System.out.println(Placer[currentColumn][currentRow]);
            System.out.println(Placer[currentColumn][++currentRow]);
            System.out.println(Placer[currentColumn][currentRow + 2]);
            currentColumn++;
        }

    }
}

最佳答案

Placer 是一个 int[2][2]...但您正在尝试访问 Placer[currentColumn][2]。对于大小为 2 的数组,您只能访问两个索引:0 和 1。

也许您希望 Placer 成为 int[3][3]

关于java - 数组越界异常,找不到问题所在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21442914/

相关文章:

c++ - 单例中的 FunktionPointerArray

c++ - 将字符数组初始化为C++中的NULL

C 编程 - 整数/长整型到字符串表示

c++ - 具有非默认构造函数且不使用 STL 的对象数组

java - 如何使用 StringBuilder 和 Array 将字符串转换为二进制并反转?

java - 交换 JPanel 内容时闪烁

java - 如何有效地计算不包括时间 block 的时间之间的距离?

java - 如何获取返回结果的服务器的数据,我想获取该结果以更新到另一台服务器

java应用程序无法与本地主机上的mysql中的特定数据库连接,出现连接拒绝错误

java - 调用构造函数的设计模式