0

我正在编写一个程序,它从电影“千与千寻”中移动 Chichiro 的照片。我目前需要做的就是将她向左、向右、向上和向下移动。她有一个用户输入的初始位置。然后我的程序要求用户输入来移动她的 u/d/l/r。如何提示用户输入以再次移动她?它总是只是移动她并退出循环。

// Initial position
Scanner keyboard = new Scanner(System.in);
System.out.print("Starting row: ");
int currentRow = keyboard.nextInt();
System.out.print("Starting column: ");
int currentCol = keyboard.nextInt();

// Create maze
Maze maze = new Maze(numberRows, numberCols, currentRow, currentCol);

System.out.print("Move Chichiro (u/d/lr): ");

char move = keyboard.next().charAt(0);

switch (move){

    case 'u': maze.moveTo(--currentRow, currentCol); // move up 
        break;
    case 'd': maze.moveTo(++currentRow, currentCol); // move down 
        break;
    case 'l': maze.moveTo(currentRow, --currentCol); // move left 
        break;
    case 'r': maze.moveTo(currentRow, ++currentCol); // move right
        break;
    default: System.out.print("That is not a valid direction!");

}
4

2 回答 2

1

将您的代码放在一个while循环中,并包括一种退出方式,例如q按下键:

 boolean quit=false;

 //keep asking for input until a 'q' is pressed
 while(! quit) {
   System.out.print("Move Chichiro (u/d/l/r/q): ");
   char move = keyboard.next().charAt(0);     

   switch (move){
     case 'u': maze.moveTo(--currentRow, currentCol); // move up
               break;
     case 'd': maze.moveTo(++currentRow, currentCol); // move down break;
     case 'l': maze.moveTo(currentRow, --currentCol); // move left 
               break;
     case 'r': maze.moveTo(currentRow, ++currentCol); // move right
               break;
     case 'q': quit=true; // quit playing
               break;
     default: System.out.print("That is not a valid direction!");}}
  }
}
于 2013-09-22T18:05:23.493 回答
0

使用以下代码,您可以随心所欲地移动,当您想退出程序时,您只需输入 'q' :

        // Create maze
    Maze maze = new Maze(numberRows, numberCols, currentRow, currentCol);
    char move;


    do{

            System.out.print("Move Chichiro (u/d/lr): ");

        move = keyboard.next().charAt(0);

        switch (move){

            case 'u': maze.moveTo(--currentRow, currentCol); // move up 
                break;
            case 'd': maze.moveTo(++currentRow, currentCol); // move down 
                break;
            case 'l': maze.moveTo(currentRow, --currentCol); // move left 
                break;
            case 'r': maze.moveTo(currentRow, ++currentCol); // move right
                break;
            default: System.out.print("That is not a valid direction!");

        }

    }while(move != 'q');

编辑:更正

于 2013-09-22T18:06:51.503 回答