0

I have 2 Arrays, both are 4*4 arrays. I want to copy 1 element from the first array and put it into the second array, then display the second array with the new element in it. However, I'm getting an error.

I'm using a deepToString call to print the Arrays. Below is my code:

    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
       }

The line board1[a][b] = board2[a][b]; is where I'm getting a "NullPointerException". I thought it was just an assignment statement to copy one element into another array. Is there a more efficient way to copy one element and display the new array? Does anybody have an idea on how to fix this?

2
  • show the declarations of your arrays Commented Sep 19, 2013 at 13:35
  • are you instantiate your arrays board1 and board2? Commented Sep 19, 2013 at 13:36

2 Answers 2

2

Clearly, you have global variables 'board1' and 'board2'. Look where they are declared and verify that you allocated the memory. In Java, you have to allocate the array memory, something like this:

Int board1[][] = new Int[256][8];
Sign up to request clarification or add additional context in comments.

1 Comment

the board1 and board2 are arrays. the declarations are: char[] [] board1 = new char[4][4]; char[] [] board2 = new char[4][4]; I have random numbers placed into both arrays. I'm fairly certain the memory is allocated, I'm not adding to either array, I'm just trying to swap an element.
0

I'm thinking your class name is service (or it is an instance of the class you posted) from the look of code, but your show() method is not static so that it couldn't be reach from a static content if you didn't init service as a new object. Could you post the full code, so that we can check?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.