[英]Java - Move position in 2d Array based on user input (and print out current position)
我有一個程序,用戶可以在其中寫入命令U,D,R,L。 根據用戶命令,我希望位置以2D陣列移動。 例如,如果用戶寫UDUDU,那么我希望該職位“上”,“下”,“上”,“下”,“上”。 到目前為止,我只設法“一次”移動它。 我想我必須更新當前位置,在這里我遇到了麻煩,需要幫助!
例如,使用決定大小[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();
}
以及我何時何地需要“打印”數組中的位置? 在switch語句之后執行此操作似乎有錯誤嗎? 要么? 在此先感謝大家!
有道理,您只能移動一次。 用戶輸入位於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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.