简体   繁体   English

使用奇数java填充2d数组

[英]populate 2d array with odd numbers java

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? 有人可以帮忙做这个工作吗?

twoDimention[i][j] = 2*j + 1; // j instead of i
System.out.print(twoDimention[i][j]);

%d5 probably doesn't do what you think. %d5可能不会按你的想法行事。 It represents %d and 5 literal. 它代表%d5字面。 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). 如果你想为____2这样的数字保留5个字符,那么你需要%5d (但IMO太多,简单的"%3d"或者如果你不想添加任何填充"%d"应该没问题)。

So this should explain existence of 5 in 1515151515 . 所以这应该解释15151515155存在。

That printed value also suggests that values generated for first row are 1 1 1 1 1 . 该印刷值还表明为第一行生成的值为1 1 1 1 1 It happens because you are using i instead of j . 这是因为你使用的是i而不是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 . 你将产生1 3 5 7 9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM