习得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));
}
}