Java - 打印二维数组 [英] Java - printing two dimensional array
问题描述
我有一个[20] [20]二维数组,我操纵过。简而言之,我正在做一个乌龟项目,用户输入指令,如笔向上= 0和笔向下= 1.当笔向下时,单个阵列位置,例如[3] [4]标记为1 。
I have a [20][20] two dimensional array that I've manipulated. In a few words I am doing a turtle project with user inputting instructions like pen up = 0 and pen down = 1. When the pen is down the individual array location, for instance [3][4] is marked with a "1".
我的程序的最后一步是打印出20/20数组。
The last step of my program is to print out the 20/20 array.
我可以'弄清楚如何打印它我需要用X替换1
I can't figure out how to print it and I need to replace the "1" with an "X"
打印命令实际上是父类程序中类的一个方法会打电话......我知道我必须使用循环......任何帮助都会受到赞赏。
The print command is actually a method inside a class that a parent program will call...I know I have to use a loop...any help would be appreciated.
public void printGrid()
{
System.out.println...
}
推荐答案
public void printGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
并替换
public void replaceGrid()
{
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
}
}
}
你可以做到这一切一气呵成:
And you can do this all in one go:
public void printAndReplaceGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
这篇关于Java - 打印二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!