java打印二维数组,Java - 打印二维数组

博客内容涉及了一个20x20的二维数组,该数组用于记录turtle项目的用户指令,如penup和pendown。当笔落下时,对应位置标记为1。作者面临的问题是如何打印整个数组并用'X'替换所有值为1的元素。解决方案包括两个方法:一个用于打印数组,另一个用于替换1为X。这两个功能可以合并到一个方法中实现。
摘要由CSDN通过智能技术生成

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".

The last step of my program is to print out the 20/20 array.

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();

}

}

And to replace

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();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值