开关声明&用户输入

时间:2013-09-22 18:01:22

标签: java switch-statement maze

我正在编写一个程序,可以从电影“千与千寻”中移动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!");

}

2 个答案:

答案 0 :(得分: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!");}}
  }
}

答案 1 :(得分: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');

编辑:更正