我有2个数组,都是4*4数组。我想从第一个数组中复制 1 个元素并将其放入第二个数组中,然后显示其中包含新元素的第二个数组。但是,我收到错误。
我正在使用 deepToString
调用来打印数组。下面是我的代码:
public static void main(String [] args)
{
System.out.print("Enter a row and column # for your first selection?");
row = scan.nextInt(); //user enters row #
column = scan.nextInt(); //user enters column #
service.show(row, column); //row and column # passed as parameters
System.out.println(Arrays.deepToString(board1)); //this will display board1
//with the new element, leaving the rest of the elements untouched
}
Public void show(int row, int column)
{
Int a = row;
Int b = column;
board1[a][b] = board2[a][b]; //destination on left, source on right
//board1 is taking an element from index [a][b] in board2
}
行 board1[a][b] = board2[a][b];
是我收到“NullPointerException
”的地方。我以为这只是一个赋值语句,将一个元素复制到另一个数组中。是否有一种更有效的方法来复制一个元素并显示新数组?有人知道如何解决这个问题吗?
最佳答案
显然,您有全局变量“board1”和“board2”。查看它们的声明位置并验证您是否分配了内存。在 Java 中,您必须分配数组内存,如下所示:
Int board1[][] = new Int[256][8];
关于java - 尝试将二维数组中的元素复制到另一个二维数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18896076/