2013-09-22 62 views
0

我正在寫一個程序,它從電影「千與千尋」中移動奇契羅的圖片。我目前所需要做的就是移動她的左,右,上,下。她有一個用戶輸入的初始位置。然後我的程序要求用戶輸入移動她的u/d/l/r。我如何提示用戶輸入重新移動她?它總是讓她移動並退出循環。switch語句和用戶輸入

// 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!"); 

} 
+1

您甲腎上腺素編輯'開關盒'周圍的'do-while'循環。 –

回答

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!");}} 
    } 
} 
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'); 

編輯:更正

+0

是的,謝謝你 – SegFault