gpt4 book ai didi

java - switch 语句和用户输入

转载 作者:行者123 更新时间:2023-12-01 14:05:21 25 4
gpt4 key购买 nike

我正在编写一个程序,用于移动电影《千与千寻》中 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!");

}

最佳答案

将代码放入 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!");}}
}
}

关于java - switch 语句和用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18947040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com