java 如果用户没有输入有效的回答,我如何将用户返回到问题行?[closed]

lsmepo6l  于 2022-10-30  发布在  Java
关注(0)|答案(2)|浏览(202)

已关闭。此问题需要更多的focused。当前不接受答案。
**想要改进此问题吗?**更新问题,使其仅关注editing this post的一个问题。

18小时前关门了。
Improve this question
我是一个新手创造一个无聊的“冒险”游戏(如果你可以这样称呼它),我想知道我将如何把“球员”(如果你可以这样称呼他们,这将只是我)回到问题,如果他们没有输入任何有效的。
在这里我要求输入:

  1. System.out.println("Hello Sir! Would you like to have diamond or wooden armour for your journey?");
  2. System.out.print("Type D for Diamond or W for Wooden: ");
  3. String armourType = input.nextLine();

接下来,我在一个“if”语句中使用输入:

  1. if (Objects.equals(armourType, "D"))
  2. System.out.println("Very nice, diamond is much stronger!");
  3. else if (Objects.equals(armourType, "W"))
  4. System.out.println("That wouldn't have been my choice, but very well.");
  5. else
  6. System.out.println("You didn't choose one of the options!");
  7. // how could I get it to go back to the question line if the "else" occurs?

在“else”子句(子句?idk)中,我希望这样,如果用户没有输入“D”或“W”,则会返回到初始问题
我猜答案是某种循环,也许是while循环,但我脑子里想不出来。

dluptydi

dluptydi1#

我自己是个菜鸟,但我希望这能有所帮助。你可以试着在while循环之前设置一个布尔标志,当玩家(如果你可以这么叫他们,那就只有你了)选择一个给定的选项时,值会改变(F-〉T,反之亦然),它会退出循环。类似于:

  1. boolean isObjectChosen = false;
  2. while (!isObjectChosen) {
  3. if (Objects.equals(armourType, "D")) {
  4. System.out.println("Very nice, diamond is much stronger!");
  5. isObjectChosen = true;
  6. } else if (Objects.equals(armourType, "W")) {
  7. System.out.println("That wouldn't have been my choice, but very well.");
  8. isObjectChosen = true;
  9. }else {
  10. System.out.println("You didn't choose one of the options!");
  11. }
exdqitrt

exdqitrt2#

看起来有人发布了一个while循环答案。下面是一个递归替代方法:

  1. public static void main(String[] args)
  2. {
  3. Scanner input = new Scanner(System.in);
  4. System.out.println("Hello Sir! Would you like to have diamond or wooden armour for your journey?");
  5. getValidArmour(input);
  6. input.close();
  7. }
  8. private static void getValidArmour(Scanner input)
  9. {
  10. System.out.print("Type D for Diamond or W for Wooden: ");
  11. String armourType = input.nextLine();
  12. switch (armourType)
  13. {
  14. case "D" -> System.out.println("Very nice, diamond is much stronger!");
  15. case "W" -> System.out.println("That wouldn't have been my choice, but very well.");
  16. default ->
  17. {
  18. System.out.println("You didn't choose one of the options!");
  19. getValidArmour(input);
  20. }
  21. };
  22. }
展开查看全部

相关问题