gpt4 book ai didi

java - 循环中的 Switch 语句重复次数未知

转载 作者:行者123 更新时间:2023-12-01 17:35:18 24 4
gpt4 key购买 nike

嗨,我正在做一个小任务,我需要构建一个重复次数未知的循环。我的代码有一个问题,当用户输入字符时,输出会无限显示。我该如何解决这个问题?

String[] action = {"x", "u", "d", "l", "r", "s", "h", "e"}; 

System.out.println("Please enter an action");

String input = sc.next();

char selection;

do{
selection = input.charAt(0);

switch(selection){

case 'x': System.out.print("Bye!");
break;
case 'u' : System.out.print("You go one square up.");
break;
case 'd': System.out.print("You go one square down.");
break;
case 'l': System.out.print("You go one square left.");
break;
case 'r': System.out.print("You go one square right.");
break;
case 's': System.out.print("You search the square for treasure. You find nothing.");
break;
case 'h': System.out.print("You hide, waiting for enemies to come by. It gets boring after about an hour and a half, so you give up.");
break;
case 'e': System.out.print("You eat some food. You regain 0 hit points");
break;
case 'z':
break;
default:
System.out.println("I dont understand");
break;
}
}
while (selection != 'z');
```

最佳答案

sc.next() 暂停执行,直到用户进行输入。
但是,由于它位于循环之外,因此它不会停止读取新输入。
因此,您需要将 next() 调用移至循环中。

do{
String input = sc.next();
selection = input.charAt(0);

switch(selection){
// rest of the code

}

关于java - 循环中的 Switch 语句重复次数未知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61053313/

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