有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我正在尝试制作一个看起来像PC终端的基于文本的游戏,我找不到方法告诉用户他们是否使用了错误的句子

//Code up
if (userinput.contains(help)) {
//Go on with the game
}
else {
System.out.println("Im sorry , couldnt understand that"); //here is where i want to go back up and 
                                                            repeat the command 
}

我尝试了初学者所知道的几乎所有东西,但什么都没有做,在我的情况下循环不起作用(也许你能找到一种方法),如果我让if这样的游戏结束,如果你得到错误的答案(一些来自文本),一些帮助将是伟大的!Thx:D


共 (3) 个答案

  1. # 1 楼答案

    您可以使用“递归”函数(一个调用自身的函数)

    因此,在这种情况下,您可以执行以下操作:

    public void getAndParseInput(){
      String userInput = getUserInput() // Use whatever you're using to get input
      if(userInput.contains(help)){ 
        // If the user input contains whatever the help is (note: if you're looking for the specific word help, it needs to be in speech marks - "help").
        continueWithGame...
      }else{
        System.out.println("Im sorry , couldnt understand that");
        this.getAndParseInput();
      }
    }
    
    
  2. # 2 楼答案

    您需要将该代码放入while循环中,并建立退出条件

    boolean endGame = false;
    
    /* Here read userinput */
    
    While(!endGame) {
      if (userinput.contains(help)) {
        //Go on with the game
      } else if(userinput.contains("quit"){
        endGame = true;
      } else {
        System.out.println("Im sorry , couldnt understand that"); //here is where i want to go back up and 
                                                                repeat the command 
      }
    
      /* Here read userinput */
    
    }
    
  3. # 3 楼答案

    下面的代码与您的代码类似,请根据需要对代码进行适当的更改以重用代码。

    代码如下所示。
    1.从控制台扫描输入
    2.将扫描的输入与字符串“help”进行比较
    3.如果扫描的输入与帮助匹配,则继续执行
    4.否则,如果用户想继续,则可以按 字母“C”并继续执行
    5.如果用户未按“C”,则控件将中断while循环 并从执行中出来

        public void executeGame() {
             Scanner scanner = new Scanner(System.in);
             String help = "help";
             while(true) {
                System.out.println("Enter the input for execution");
                String input = scanner.nextLine();
                if (input.contains(help)){
                   System.out.println("Continue execution");
                } else {
                   System.out.println("Sorry Wrong input.. Would you like to continue press C");
                   input = scanner.nextLine();
                   if (input.equals("C")){
                      continue;
                   } else {
                      System.out.println("Sorry wrong input :"+input);
                      System.out.println("Hence Existing....");
                      System.exit(0);
                   }
              }
          }
        }