![](/img/trans.png)
[英]How to find the amount of odd numbers and thee sum of all odd numbers in a inputted 2D array java?
[英]populate 2d array with odd numbers java
我需要用奇数填充二维数组。
我希望它看起来像这样
13579
13579
13579
13579
这是我到目前为止:
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();
}
它打印:
1515151515
3535353535
5555555555
7575757575
9595959595
有人可以帮忙做这个工作吗?
twoDimention[i][j] = 2*j + 1; // j instead of i
System.out.print(twoDimention[i][j]);
%d5
可能不会按你的想法行事。 它代表%d
和5
字面。 如果你想为____2
这样的数字保留5个字符,那么你需要%5d
(但IMO太多,简单的"%3d"
或者如果你不想添加任何填充"%d"
应该没问题)。
所以这应该解释1515151515
中5
存在。
该印刷值还表明为第一行生成的值为1
1
1
1
1
。 这是因为你使用的是i
而不是j
。 如果你改变你的
twoDimention[i][j] = 2*i + 1;
至
twoDimention[i][j] = 2*j + 1;
你将产生1
3
5
7
9
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.