【问题标题】:While loop which takes user input if there is any, executes on its own otherwise?如果有任何用户输入,while循环会自行执行,否则会自行执行吗?
【发布时间】:2019-06-12 02:39:34
【问题描述】:

我正在制作一个 while 循环,它将每 1/3 秒左右执行一次(对于 Snake 游戏)。如果有输入,我希望循环能够处理扫描仪输入,如果没有用户输入,我希望循环执行一些默认任务(在最后一个输入方向移动蛇)。

我知道一个更简单的方法是创建一个带有事件处理程序的 javafx 程序,但是我只是想看看我是否可以在终端中为个人项目实现这种游戏。每当我在 while 循环中打开 Scanner 时,我都会将一个变量设置为默认值。如果 sc.nextLine() 存在,扫描仪将更新此变量。然后我的循环做它的事。问题是,即使 sc.nextLine() 不存在,无论我如何表达我的代码,我的循环都会等待输入。

如果我从循环中删除扫描仪,代码会在计时器上完美执行,使用默认输入,但是一旦我使用扫描仪查找用户输入,它就会暂停。

while(snek.currSnake.gameState){
  if(snek.nextTurnTime - System.currentTimeMillis() > 0){
    try{
      TimeUnit.MILLISECONDS.sleep(snek.nextTurnTime- 
      System.currentTimeMillis());
    }
    catch(InterruptedException e){
      break;
    }
    //This section handles how quickly each turn gets executed
  }


  System.out.println(snek.currSnake);  //Print game board to terminal

  char charInput = snek.currInput;  //Update charInput to some
                                    //default value
  if(scanner.hasNext()){
    charInput = scanner.nextLine().charAt(0);
  } 
                      //If there is user input, update charInput to that


  if(charInput == 'w' || charInput == 'a' || charInput == 's'
  || charInput == 'd' || charInput == 'q'){  //If charInput is defined
    snek.currInput = charInput;
    snek.currSnake.move(charInput);  //Move snake and update default value
  }
  snek.nextTurnTime = System.currentTimeMillis() + TURN_DELAY_VAL;
}

我希望 while 循环自行执行,如果有下一个用户输入,则运行代码,现在不是使用默认输入,而是使用用户输入的输入。

相反,每转一圈,while 循环就会暂停,等待scanner.nextLine() 为真,每次都需要用户输入。

我收到错误消息,只是预期结果与我得到的结果之间存在差距

【问题讨论】:

  • 看看这个问题。它可能适用。 stackoverflow.com/questions/5853989/time-limit-for-an-input
  • 哇,这真是个好主意!所以基本上我可以设置一个 TimerTask,如果它没有在需要的时间内完成,我可以告诉它退出吗?
  • 支持ScheduledExecutorService 胜过TimerTimerTask
  • 经过仔细检查,计时器任务会退出整个 Java 应用程序,并且不会像您预期的那样在您的用例中工作。我添加了一个答案,我相信它会满足您的需求。

标签: java


【解决方案1】:

如果您想在设定的时间范围内轮询用户的输入,您可以执行以下操作示例。

public static void main(String[] args) throws IOException, InterruptedException {
    // wait time of 1/3 a second in milliseconds
    long waitTime = (long) ((1.0 / 3.0) * 1000.0);
    // standard input buffered reader
    try (BufferedReader in = new BufferedReader(new InputStreamReader(System.in))) {
        // loop for 100 polls used in testing (replace with game loop here)
        for (int i = 0; i < 100; i++) {
            // wait for user to input data
            Thread.sleep(waitTime);
            String s = null;
            while (in.ready()) {
                // get the last thing the user has input in the 1/3 second
                // to protect you from multiple inputs
                s = in.readLine();
            }
            if (s != null) {
                // handle user input here
                System.out.println("User input: " + s);
            } else {
                // handle no user input here
            }
        }
    }
}

【讨论】:

  • 太棒了!这看起来是一个非常酷的解决方案,所以你可以告诉程序在你告诉你的线程睡眠的同时寻找输入?另外,为什么在某些情况下人们更喜欢使用 BufferedReader 而不是 Scanners?扫描仪不能很好地处理这个任务吗?
  • 老实说,扫描仪在这种情况下应该可以正常工作,您可以轻松地将缓冲阅读器替换为适合您的用例的阅读器。根据我的经验,缓冲阅读器通常用于较大的文件 io 操作,而这恰好是我从中得出这个想法的示例中使用的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-06
  • 1970-01-01
  • 2018-08-13
  • 2021-12-12
相关资源
最近更新 更多