[英]How can I use a for loop to create a two dimensional array and assign linear values with an increment of 10?
I want to create a two dimensional array using a for loop and I want to assign values with an increment of 10. So far here is what I have and I am not getting the result I want...我想使用 for 循环创建一个二维数组,并且我想以 10 的增量分配值。到目前为止,这就是我所拥有的,但我没有得到我想要的结果......
package ~/TwoDimensionalArray;
import java.util.Scanner;
public class TwoDimensionalArray {
public static void main(String[] args) {
int rows = 3;
int columns = 3;
int[][] array = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
array[i][j] = j * 10;
System.out.println(array[i][j]);
}
}
}
}
Here is what I want my output to be:这是我希望我的 output 成为的内容:
0 30 60
10 40 70
20 50 80
Process finished with exit code 0
Here is what I keep getting:这是我不断得到的:
0
10
20
0
10
20
0
10
20
Process finished with exit code 0
j * 10 * rows + i * 10
.您应该使用公式j * 10 * rows + i * 10
计算第 i 行第 j 行的数字。 This gives you the correct number at each position.这将为您提供每个 position 的正确编号。int rows = 3;
int columns = 3;
int[][] array = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
array[i][j] = j * 10 * rows + i * 10;
System.out.print(array[i][j]); // "print" doesn't print a new line
System.out.print("\t"); // print a tab!
}
System.out.println(); // print a new line here
}
maybe this is what u want也许这就是你想要的
public class TempTest {
static final int ROW = 3;
static final int COLUMN = 3;
public static void main(String[] args) {
int[][] array = new int[ROW][COLUMN];
// assign values to array
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COLUMN; j++) {
array[i][j] = 10 * (i + 3 * j);
}
}
// display array
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COLUMN; j++) {
System.out.print(array[i][j]);
System.out.print(' ');
}
System.out.println();
}
}
}
and the result will be结果将是
0 30 60
10 40 70
20 50 80
I think u are not familiar with the difference between print
and println
, the latter one will add a new line.我想你不熟悉print
和println
之间的区别,后者会添加一个新行。 Try learn more about JAVA, good luck!尝试了解更多关于 JAVA 的信息,祝你好运!
Try this.尝试这个。
int rows = 3;
int columns = 3;
int[][] array = new int[rows][columns];
for (int i = 0, v = 0; i < rows; i++) {
for (int j = 0; j < columns; j++, v += 10) {
array[i][j] = v;
System.out.print(array[i][j] + "\t");
}
System.out.println();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.