3

I need to populate a 2d array with odd numbers.

I want it to look like this

13579
13579
13579
13579

This is what I have so far:

    public static void twoDArray(){

    //http://stackoverflow.com/questions/11243774/how-to-automatically-populate-a-2d-array-with-numbers
    int twoDimention[][] = new int[5][3];

    for(int i=0; i<twoDimention.length; i++){
        for(int j=0; j<twoDimention[i].length; j++){
            twoDimention[i][j] = 2*i + 1;


            System.out.printf("%d5", twoDimention[i][j]);
        }
        System.out.println();
    }

It prints:

1515151515
3535353535
5555555555
7575757575
9595959595

Can someone help make this work?

epascarello
  • 204,599
  • 20
  • 195
  • 236
Tim B.
  • 446
  • 1
  • 5
  • 13

2 Answers2

1
twoDimention[i][j] = 2*j + 1; // j instead of i
System.out.print(twoDimention[i][j]);
David Frank
  • 5,918
  • 8
  • 28
  • 43
1

%d5 probably doesn't do what you think. It represents %d and 5 literal. If you wanted to reserve 5 characters for digit like ____2 then you need %5d (but IMO it is too much, simple "%3d" or if you don't want to add any padding "%d" should be fine).

So this should explain existence of 5 in 1515151515.

That printed value also suggests that values generated for first row are 1 1 1 1 1. It happens because you are using i instead of j. If you change your

twoDimention[i][j] = 2*i + 1;

to

twoDimention[i][j] = 2*j + 1;

you will generate 1 3 5 7 9.

Pshemo
  • 122,468
  • 25
  • 185
  • 269