[英]Trying to copy an element in a 2D array into another 2D array
我有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];
我認為您的類名是服務(或者它是您發布的類的實例),但是您的show()方法不是靜態的,因此如果您無法從靜態內容訪問它沒有將init服務作為新對象。 你可以發布完整的代碼,以便我們檢查嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.