java - 尝试将二维数组中的元素复制到另一个二维数组中

标签 java arrays copy element

我有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/

相关文章:

macos - Mac OSX/cocoa - 获取带有 NSPasteBoard 项目的原始数据的位置路径字符串

java - 我的 Java 程序无法编译

iphone - objective-c : a C int array in a class interface?

java - 使用 Spring Data JPA Stream 获取数据

arrays - 将 bsxfun 或 arrayfun 应用于矩阵的每一行

python - 如何在 python 中定义多维数组?

C++ std::copy 输入迭代器(指针)到 vector

Java - 包含对原始列表的引用的克隆列表

java - getActivity 未找到 PendingIntent

java - @RequestBody 变量返回 null 属性