-1

I am trying to write a nested for loop that will print out the values of the following code in a specific order:

public static void main(String[] args) {

    int[][] array2d = new int[3][5];
    for (int i = 0; i < array2d.length; i++) {
        for (int j = 0; j < array2d[0].length; j++) {
            array2d[i][j] = (i * array2d[0].length) + j + 1;
        }
    }

    for (int x = 0; x <= 4; x++) {
        for (int y = 0; y <= 2; y++) {
            System.out.println(array2d[y][x]);
        }
    }
}

}

The current array prints the way I want it, but each printout on a separate line.

I want the output (on a single line) to be this:

1 6 11 2 7 12 3 8 13 4 9 14 5 10 15

Thanks for the help.

user2057847
  • 47
  • 1
  • 1
  • 8

4 Answers4

1

Replace println with print and it should work

Simon Verhoeven
  • 1,295
  • 11
  • 23
1

You can use System.out.print instead:

System.out.print(array2d[y][x] + " ");
Marc Baumbach
  • 10,323
  • 2
  • 30
  • 45
1
String s = "";
for (int i = 0; i < array2d.length; i++) {
    for (int j = 0; j < array2d[i].length; j++) {
        s += array2d[i][j] + " ";
    }
}
System.out.println(s);
dan
  • 155
  • 8
  • The for loops are reversed, so this won't produce the correct result. I would also suggest using a `StringBuilder` instead of string concatenation. – Marc Baumbach Feb 12 '13 at 21:47
0
public static void main(String[] args) {
    int[][] array2d = new int[3][5];
    for (int i = 0; i < array2d.length; i++) {
        for (int j = 0; j < array2d[0].length; j++) {
           array2d[i][j] = (i * array2d[0].length) + j + 1;
        }
    }
    StringBuilder builder = new StringBuilder();
    for (int x = 0; x <= 4; x++) {
        for (int y = 0; y <= 2; y++) {
            builder.append(array2d[y][x]);
            if(!(x == 4 && y == 2)){
                builder.append(" ");
            }
        }
    }
    System.out.println(builder.toString());
}

You basically had it right, except for changing the println to be print and formatting the string how you want. I changed it a little to show how the StringBuilder works. Whenever possible I use a StringBuilder because it is more convenient.

fudge22it
  • 103
  • 1
  • 2
  • 13