我有一个程序,用户在命令U,D,R,L中写入。根据用户命令,我希望位置在2D数组中移动。例如,如果用户编写了UDUDU,那么我希望该位置可以进入' '下' '向上' '下' '向上&#39 ;.到目前为止,我只能设法移动它一次"。我想我必须更新当前的位置,它在这里我遇到了麻烦,我需要帮助!
例如,使用决定尺寸[3] [3]和位置[1] [1]。
0 1 2
0 0 0 0
1 0 1 0
2 0 0 0
如果用户按下UDUDU,那么新位置就像这样(在这种情况下x为+1)
0 1 2
0 0 0 0
1 0 0 0
2 0 1 0
以下是代码:
Scanner scan = new Scanner(System.in);
System.out.println("Enter length(x) and width(y)");
x = scan.nextInt();
y = scan.nextInt();
int[][] roomsize = new int[x][y];//The array
System.out.println("Enter the starting position");
x = scan.nextInt();
y = scan.nextInt();
roomsize[x][y] = 1; //Starting position
System.out.println("Enter commands U(up), D(down), R(right) or L(left)");//User input
String command = scan.next();
for (char directionCommand : command.toCharArray()){
move(directionCommand, roomsize, x, y);
}
//Should I print it out here? It
/*for(int i = 0; i < roomsize.length; i++)
{
for(int j = 0; j < roomsize[i].length; j++)
{
System.out.print(roomsize[i][j]);
if(j < roomsize[i].length - 1) System.out.print(" ");
}
System.out.println();
}*/
public static void move(int i, int[][] roomsize, int x, int y){
int px = 0;//Current position
int py = 0;//Current position
switch(i){
case 'U': px+=1; break;//Is this the right way to update position?
case 'D': roomsize[x-1][y]; break;//Or this waY?
case 'R': roomsize[x][y+1] = 1; break;
case 'L': roomsize[x][y-1] = 1;break;
default:; break;
}
roomsize[px][py] = 1;//Do I set the new position like this?
for(int i1 = 0; i1 < roomsize.length; i1++)
{
for(int j = 0; j < roomsize[i1].length; j++)
{
System.out.print(roomsize[i1][j]);
if(j < roomsize[i1].length - 1) System.out.print(" ");
}
System.out.println();
}
还有我需要的时间和地点&#34;打印出来&#34;数组中的位置?在switch语句之后完成它似乎是错误的吗?要么?先谢谢你们!
答案 0 :(得分:0)
有道理,您只能移动一次。您的for循环之外有用户输入。
String command = scan.next();
在循环之前读入,然后命令长度用作for循环
for (char directionCommand : command.toCharArray())
我会尝试使用while循环
Scanner scan = new Scanner(System.in);
System.out.println("Enter length(x) and width(y)");
x = scan.nextInt();
y = scan.nextInt();
int[][] roomsize = new int[x][y];//The array
System.out.println("Enter the starting position");
x = scan.nextInt();
y = scan.nextInt();
roomsize[x][y] = 1; //Starting position
while(true){
System.out.println("Enter commands U(up), D(down), R(right), L(left), and Q(quit)");//User input
String command = scan.next();
if(command.equalsIgnoreCase("Q"){
break;
}
move(command.charAt(0), roomsize, x, y);
}