简体   繁体   English

Java多维数组中的元素修改

[英]Element Modification in Multi-Dimensional Arrays in Java

I have created a 2-D array in Java and I wish to change the value of each element. 我已经用Java创建了一个二维数组,并且希望更改每个元素的值。

Here is what I am trying to accomplish 这是我想要完成的

-number each student from 1-10 -从1-10开始为每个学生编号

-give each student 5 random marks from 40-100 -给每个学生40-100的5个随机分数

int[][] students = new int[10][5];
Random numGen = new Random();

for (int i=0; i < students.length; i++){
    students[i] = i;         //Problem here..        
    for (int j=0; j<5; j++){
        students[i][j] = numGen.nextInt(40)+61
    }
}

I am having issues assigning each student a number from 1-10. 我在分配每个学生1到10之间的数字时遇到问题。

Where I wrote '//Problem here', is where the compiler keeps giving me trouble. 我在这里写“ //问题”的地方是编译器不断给我带来麻烦的地方。

What is the appropriate method for modifying a single element in multi-dimension arrays? 修改多维数组中单个元素的合适方法是什么?

Just use the index into the students (and return id as index+1 when you need to). 只需在学生中使用索引即可(并在需要时将id返回为index + 1)。

int[][] students = new int[10][5];
Random numGen = new Random();

for (int i=0; i < students.length; i++){     
    for (int j=0; j<5; j++){
        students[i][j] = numGen.nextInt(40)+61
    }
}

Array indices in java starts from 0 . Java中的数组索引从0开始。 Which means 1st row is represented as 0. To edit an element in a 2D array you need to specify the both indices. 这意味着第一行表示为0。要编辑2D数组中的元素,您需要指定两个索引。 For example to edit an element at 5th row and 4th column you should use myArray[4][3] . 例如,要编辑5th row4th column的元素,应使用myArray[4][3] Because you start counting from 0. myArray[0][0] is first element of the first row. 因为您从0开始计数myArray[0][0]是第一行的第一元素。

int[][] students = new int[10][5];
Random numGen = new Random();

for (int i=0; i < students.length; i++){
    students[i][0] = i; //Change student[i] = i to student[i] = i+i
                        // because i starts  from 0 but student number starts from 1.       
    for (int j=0; j<5; j++){
        students[i][j] = numGen.nextInt(40)+61
    }
}

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

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