[英]How do I make my two-dimensional array show horizontally as well as vertically in java?
我正在尝试制作一个生成 0-50 的随机数的二维数组。 它可以工作,但不会生成包含列和行的 3 x 5 布局。
我试过改变 i 和 j 并使用不同的变量。
/**
* Constructor for objects of class GenerateLithium
*/
public GenerateLithium()
{
randomGenerator = new Random();
}
public void generateSample()
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 3; j++)
{
tray[i][j] = i * j;
tray[i][j] = grading++;
grading = randomGenerator.nextInt(50);
System.out.print(" ");
}
}
}
public void printTray()
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 3; j++)
{
System.out.println(tray[i][j] + " ");
}
System.out.println("");
}
}
现在结果:
45
22
11
23
1
35
45
43
22
13
15
3
0
16
42
预期结果:
45
22
11
23
1
35
45
43
22
13
15
3
0
16
42
public void printTray()
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 3; j++)
{
System.out.print(tray[i][j] + "/t ");
}
System.out.println("");
}
}
用printTray()
方法中的System.out.print
替换第一个System.out.println
。
您可以这样做以将数组 2D 的 output 显示为网格布局:
public void printTray()
{
for (int[] x : tray) {
System.out.println(Arrays.toString(x));
}
}
这是一个完整的 GenerateLithium class,可打印 3 x 5 表。
class GenerateLithium{
Random randomGenerator;
int[][] tray = new int[5][3];
int grading;
public GenerateLithium() {
randomGenerator = new Random();
}
public static void main(String args[]) throws UnsupportedEncodingException {
GenerateLithium m = new GenerateLithium();
m.generateSample();
m.printTray();
}
public void generateSample() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 3; j++) {
tray[i][j] = i * j;
tray[i][j] = grading++;
grading = randomGenerator.nextInt(50);
}
}
}
public void printTray() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(tray[i][j] + "\t");
}
System.out.println();
}
}
}
结果:
0 8 14
29 33 20
18 37 10
33 21 2
8 45 29
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.