习得Java不久,请高手指教 :)
public class DrawLines {
public String[] execute(String[] commands){
final int LIMITX=20, LIMITY=20;
char[][] canvas=new char[LIMITX][LIMITY];
final char ink='X', blank='.';
int direction;
final int RIGHT=0, UP=1, LEFT=2, DOWN=3;
final int[][] offset={{1,0}, {0,-1}, {-1,0}, {0,1}}; // x,y offset of each direction
int x, y;
//init canvas
for(y=0; y<LIMITY; y++)
for(x=0; x<LIMITX; x++)
canvas[y][x]=blank;
//init cursor
x=y=0;
direction=DOWN;
//canvas[y][x]=ink; the problem may be a fault about the cursor init behavior
//process commands
for(int i=0; i<commands.length; i++){
if(commands[i].equals("LEFT")){ //command LEFT
direction=(direction+1)%4;
}else if(commands[i].startsWith("FORWARD")){ //command FORWARD
canvas[y][x]=ink; // only for first pixel!! sigh...
int step=Integer.parseInt( commands[i].substring(8) );
for(int j=0; j<step; j++){
canvas[y+=offset[direction][1]][x+=offset[direction][0]]=ink;
}
}
}
String[] result = new String[LIMITY];
for(int i=0; i<LIMITY; i++){
result[i]=new String(canvas[i]);
}
return result;
}
private static void draw(String[] line){
for(int i=0; i<line.length; i++){
System.out.println(line[i]);
}
}
public static void main(String[] args) {
String[] cmd0= {"FORWARD 19", "LEFT", "FORWARD 19", "LEFT", "FORWARD 19", "LEFT", "FORWARD 19"};
String[] cmd1= {"LEFT", "LEFT", "LEFT", "LEFT", "LEFT", "LEFT", "LEFT", "LEFT"};
String[] cmd2={"FORWARD 1"};
String[] cmd3={"LEFT", "FORWARD 19", "LEFT", "LEFT", "LEFT",
"FORWARD 18", "LEFT", "LEFT", "LEFT", "FORWARD 17",
"LEFT", "LEFT", "LEFT", "FORWARD 16", "LEFT",
"LEFT", "LEFT", "FORWARD 15", "LEFT", "LEFT", "LEFT",
"FORWARD 14", "LEFT", "LEFT", "LEFT", "FORWARD 13",
"LEFT", "LEFT", "LEFT", "FORWARD 12", "LEFT", "LEFT",
"LEFT", "FORWARD 11", "LEFT", "LEFT", "LEFT", "FORWARD 10",
"LEFT", "LEFT", "LEFT", "FORWARD 9", "LEFT", "LEFT",
"LEFT", "FORWARD 8", "LEFT", "LEFT", "LEFT", "FORWARD 7"};
DrawLines d=new DrawLines();
draw(d.execute(cmd0));
draw(d.execute(cmd1));
draw(d.execute(cmd2));
draw(d.execute(cmd3));
}
}
博主刚学习Java,分享了一个DrawLines类的代码。该类通过execute方法处理命令数组,在二维字符数组canvas上绘制线条,支持LEFT和FORWARD命令,最后将结果存储在字符串数组中并输出。代码还给出了多个命令数组示例进行测试。
7144

被折叠的 条评论
为什么被折叠?



