简体   繁体   English

创建2D数组并将每个元素初始化为i * j的值,其中i和j是2个索引(例如,元素[5] [3]为5 * 3 = 15)

[英]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.

相关问题 Java:二维数组的总和,其中M [i] [j] =(int)i / j - Java: Sum of 2D array where the M[i][j] = (int) i/j 我想创建一个具有特殊属性的2d静态数组,其中每个元素都是一对元素的哈希图? - I want to create a 2d static array with a special property where each element will be a hash map of a pair of elements? 使用arrayName [i] [j] .equalsIgnoreCase在2D数组中进行Java搜索找不到值 - Java Search In 2D Array using arrayName[i][j].equalsIgnoreCase not finding value 我如何只反转二维布尔数组中的每个第二个元素? - How would I only invert every second element in a 2D boolean array? 二维数组,其中每个元素都是一个列表 - 2D Array where each element is a List 给定未排序的数组,找到A [j] - A [i]的最大值,其中j> i..in O(n)时间 - Given an unsorted Array find maximum value of A[j] - A[i] where j>i..in O(n) time 使用二维双数组字面量初始化 Java 对象数组元素 - Initialize Java Object array element with 2D double array literal 使用每个元素的邻居的 2D 数组中每个元素的中值 - Median of every element on a 2D array using the neighbors of each element 查找数组中A [i] * A [j]&gt; A [i] + A [j]的对数 - Finding number of pairs in array where A[i] * A[j] > A[i] + A[j] 如何检查二维数组中的对角线元素是否被占用? - How can I check if a diagonal element in 2D array is occupied?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM