[英]Create a 2D array and initialize every element to be the value of i * j where i and j are the 2 indices (for instance, element [5][3] is 5 * 3 = 15)
I am truly stuck here on how to do this. 我确实对如何执行此操作感到困惑。 I got as far as creating the 10x10 array and making variables i and j - not far at all.
我可以创建10x10数组并创建变量i和j-一点也不远。 I thought about the use of loops to initialize every element, but I just don't know how to go about doing it.
我考虑过使用循环来初始化每个元素,但是我只是不知道该怎么做。 Any help is appreciated, thanks.
任何帮助表示赞赏,谢谢。
public class arrays { 公共类数组{
public static void main(String[] args) {
int[][] array = new int[10][10];
int i = 0, j = 0;
}
} }
I was thinking of using a do while loop or for loop. 我当时在考虑使用do while循环或for循环。
Create two nested for
loops, one for i
, and one for j
, looping over all valid indices. 创建两个嵌套的
for
循环,一个用于i
,一个用于j
,循环所有有效索引。 In the body of the inner for
loop, assign the computed product to the 2D array element. 在内部
for
循环的主体中,将计算出的乘积分配给2D数组元素。
Psuedo-code: 伪代码:
for i = 0 to 9
for j = 0 to 9
array[i][j] = i*j
Converting this to Java should be a snap. 将其转换为Java应该很容易。
You will need two for loops inside each other: 彼此之间将需要两个for循环:
int[][] array = new int[10][10];
for (int x = 0; x < array.length; ++x)
{
for (int y = 0; y < array[y].length; ++y)
{
int product = x * y;
// put the value at the right place
}
}
You can read this as: 您可以将其读取为:
For each x value, iterate over the ten y values and do...
对于每个x值,迭代十个y值并执行...
int [][] array = new int[10][10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
//initialize every element
array[i][j] = i + j;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.