Adam Ackerman Adam Ackerman - 3 months ago 6
Java Question

Java fixing my multidimensional array poplulating

Trying to get a multidimensional array in java populated as such:
Created by passing height and width 10 & 10 with a multiplier of 10

Expected Output:

(0,10)
(0,20)
(0,30)
(0,40)
(0,50)
(0,60)
(0,70)
(0,80)
(0,90)

(10,10)
(10,20)
(10,30)
(10,40)
(10,50)
(10,60)
(10,70)
(10,80)
(10,90)

(20,10)
(20,20)
(20,30)
etc...

Code:

int[][] coords = new int[height][width];
int multiplier = 10;
for (int i = 0;i < height;i++) {
for (int j = 0;j < width;j++){
coords[i][j] = j*multiplier;
}
}
for (int i = 0;i < height-1;i++) {
for (int j = 0;j < width;j++){
System.out.println("(" + i + "," + coords[i][j] + ")");
}
}


Current Output:

(0,0)
(0,10)
(0,20)
(0,30)
(0,40)
(0,50)
(0,60)
(0,70)
(0,80)
(0,90)

(1,0)
(1,10)
(1,20)
(1,30)
(1,40)
(1,50)
(1,60)
(1,70)
(1,80)
(1,90)

(2,0)
(2,10)
(2,20)
(2,30)
(2,40)
(2,50)
(2,60)
(2,70)
(2,80)
(2,90)

(3,0)
(3,10)
(3,20)
(3,30)
(3,40)
(3,50)
(3,60)
(3,70)
(3,80)
(3,90)

(4,0)
(4,10)
(4,20)
(4,30)
(4,40)
(4,50)
(4,60)
(4,70)
(4,80)
(4,90)

(5,0)
(5,10)
(5,20)
(5,30)
(5,40)
(5,50)
(5,60)
(5,70)
(5,80)
(5,90)

(6,0)
(6,10)
(6,20)
(6,30)
(6,40)
(6,50)
(6,60)
(6,70)
(6,80)
(6,90)

(7,0)
(7,10)
(7,20)
(7,30)
(7,40)
(7,50)
(7,60)
(7,70)
(7,80)
(7,90)

(8,0)
(8,10)
(8,20)
(8,30)
(8,40)
(8,50)
(8,60)
(8,70)
(8,80)
(8,90)

Answer

Changes to match your desired output:

  • j initial value changed to 1
  • printing new line only in outer loop
  • multiplying i by 10 when printing

_

int[][] coords = new int[height][width];
int multiplier = 10;
for (int i = 0;i < height;i++) {
    for (int j = 1;j < width;j++){
        coords[i][j] = j*multiplier;
    }
}
for (int i = 0;i < height-1;i++) {
    for (int j = 1;j < width;j++){
        System.out.print("(" + i*multiplier + "," + coords[i][j] + ")");
    }
    System.out.println();
}