我正在写一个程序,把千寻的照片从电影“千与千寻”中移走。我现在要做的就是左右上下移动她。她具有用户输入的初始位置。然后我的程序要求用户输入来移动她的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!");
}发布于 2013-09-23 02:05:23
将您的代码放在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-23 02:06:52
WIth下面的代码你可以随意移动,当你想退出程序时,你只需要输入'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');编辑:更正
https://stackoverflow.com/questions/18947040
复制相似问题