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