我尝试使用一维数组打印3x3随机0和1表。之后我想打印由全1或全0组成的线(有点像tic tac toe),但是现在我无法获得我需要的3x3显示器。
int[] row1 = new int[3];
int[] row2 = new int[3];
int[] row3 = new int[3];
for (int i = 0; i < 3; i++)
{
row1[i] = (int)(Math.random() * 2);
row2[i] = (int)(Math.random() * 2);
row3[i] = (int)(Math.random() * 2);
System.out.print(row1[i]);
System.out.print("\n");
System.out.print(row2[i]);
System.out.print(row3[i]);
}
输出(布局)是:
0
001
110
00
这是我最接近显示三行三列的数字。我尝试过print,println和printf,但我无法得到它。我知道可能会有一些不必要的代码但是在这一点上我不知所措。任何帮助表示赞赏。
答案 0 :(得分:2)
您需要在之后放置换行符三个print
语句显示一行:
for (int i = 0; i < 3; i++) {
row1[i] = (int) (Math.random() * 2);
row2[i] = (int) (Math.random() * 2);
row3[i] = (int) (Math.random() * 2);
System.out.print(row1[i]);
System.out.print(row2[i]);
System.out.print(row3[i]);
System.out.print("\n");
}
在这种情况下,最好将数组重命名为col1
,col2
和col3
,因为每次迭代都会通过从列中选择一个元素来打印一行。由于你是随机生成0和1,所以不应该有所不同。
int[] col1 = new int[3];
int[] col2 = new int[3];
int[] col3 = new int[3];
for (int i = 0; i < 3; i++) {
col1[i] = (int) (Math.random() * 2);
col2[i] = (int) (Math.random() * 2);
col3[i] = (int) (Math.random() * 2);
System.out.print(col1[i]);
System.out.print(col2[i]);
System.out.print(col3[i]);
System.out.print("\n");
}
答案 1 :(得分:1)
由于您的变量被命名为行,因此它们不应显示为填充数字。
用数字填充行后,单独循环并打印它们。
int[] row1 = new int[3];
int[] row2 = new int[3];
int[] row3 = new int[3];
// Fill your rows with numbers
for (int i = 0; i < 3; i++)
{
row1[i] = (int)(Math.random() * 2);
row2[i] = (int)(Math.random() * 2);
row3[i] = (int)(Math.random() * 2);
}
printRow(row1);
printRow(row2);
printRow(row3);
printRow方法如下所示:
private void printRow(int[] row)
{
for (int i = 0; i < row.length; i++)
{
System.out.print(row[i]);
}
System.out.print("\n");
}
然后你的输出看起来像(根据分配的随机数):
010 101 010
答案 2 :(得分:0)
public static void main (String[] args) throws java.lang.Exception
{
int[] row1 = new int[3];
int[] row2 = new int[3];
int[] row3 = new int[3];
for (int i = 0; i < 3; i++)
{
row1[i] = (int)(Math.random() * 2);
row2[i] = (int)(Math.random() * 2);
row3[i] = (int)(Math.random() * 2);
}
for (int i : row1)
{
System.out.print(i);
}
System.out.print("\n");
for (int i : row2)
{
System.out.print(i);
}
System.out.print("\n");
for (int i : row3)
{
System.out.print(i);
}
System.out.print("\n");
}