0

This program is supposed to scale an array holding objects in each cell by a factor of two. For example, the array:

[[Object1,Object2],
 [Object3,Object4]]

should become:

[[Object1,Object1,Object2,Object2],
 [Object1,Object1,Object2,Object2],
 [Object3,Object3,Object4,Object4],
 [Object3,Object3,Object4,Object4]]

This is the code I have for the program so far:

public Color[][] doOperation(Color[][] imageArray)
{
    int multiplier = 2;  
    Color[][] newArray = new Color[imageArray.length*2][imageArray[0].length*2];

    for(int i = 0; i < imageArray.length; i++)
        for(int j = 0; j < imageArray[0].length; j++)
        {
            newArray[i][j] = imageArray[i/multiplier][j/multiplier];
        }
}

How should I change this code so that the new array is scaled properly? Any help is appreciated.

azro
  • 53,056
  • 7
  • 34
  • 70
Marco Aiello
  • 179
  • 10
  • 1
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Joe C Feb 05 '19 at 21:42
  • What do you get actually ? – azro Feb 05 '19 at 21:46
  • What I get is a NullPointerException in a different method (given to me as part of the assignment) that is meant to get values for red,green and blue for each element of the original array, since each cell of the original array represent a pixel in an image. But I know that the problem is in the way that I am trying to copy the pixels into new cells, and not the other code. – Marco Aiello Feb 05 '19 at 21:51

2 Answers2

2

You should be looping over the newArray, not imageArray.

Example:

    int[][] oldArray = new int[2][2];
    int k = 1;
    for(int i = 0; i < oldArray.length; i++)
        for(int j = 0; j < oldArray[0].length; j++)
            oldArray[i][j] = k++; 

    int[][] newArray = new int[oldArray.length*2][oldArray[0].length*2];

    for(int i = 0; i < newArray.length; i++)
        for(int j = 0; j < newArray[0].length; j++)
            newArray[i][j] = oldArray[i/2][j/2];

    System.out.println(Arrays.deepToString(oldArray));
    System.out.println(Arrays.deepToString(newArray));

Output:

[[1, 2], [3, 4]]
[[1, 1, 2, 2], [1, 1, 2, 2], [3, 3, 4, 4], [3, 3, 4, 4]]
2

You mixed up your newArray and imageArray. You initialize double-sized newArray (this is right) but then iterate over it, using imageArray length. Just swap imageArray.length to newArray.length. And don't forget about return ;)

public static Color[][] doOperation(Color[][] imageArray) {
    int multiplier = 2;
    Color[][] newArray = new Color[imageArray.length*2][imageArray[0].length*2];

    for(int i = 0; i < newArray.length; i++)
        for(int j = 0; j < newArray[0].length; j++) {
            newArray[i][j] = imageArray[i/multiplier][j/multiplier];
        }
    return newArray;
}
Mito Uzumaki
  • 52
  • 1
  • 6