I have created a 2-D array in Java and I wish to change the value of each element.
Here is what I am trying to accomplish
-number each student from 1-10
-give each student 5 random marks from 40-100
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.
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).
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
. Which means 1st row is represented as 0. To edit an element in a 2D array you need to specify the both indices. For example to edit an element at 5th row
and 4th column
you should use myArray[4][3]
. Because you start counting from 0. myArray[0][0]
is first element of the first row.
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
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.