【问题标题】:Why is this being printed in my while loop before I type anything? [duplicate]为什么在我输入任何内容之前会在我的 while 循环中打印出来? [复制]
【发布时间】:2018-04-27 07:57:57
【问题描述】:
public static void main(String[] args) {

    char play = 0;

    System.out.println("Welcome to Tic-Tac-Toe!!");
    System.out.print("Would you like to play a game? (enter 'y' for yes or 'n' for no): ");
    play = keyboard.next().charAt(0); 

    if (play != 'y') {
        System.out.println("Goodbye!");
    }

    playGame();

    System.out.print("Would you like to play another game (enter 'y' for yes or 'n' for no): ");
    play = keyboard.next().charAt(0);

    if (play != 'y') {
        System.out.println("Goodbye!");
    }
}

// *******************************************************
private static void playGame() {    

    String move;

      System.out.print("Who should move first? (c=computer h=human): ");
      move = keyboard.nextLine();

      move = move.toLowerCase();

      while ( !move.equals("c") && !move.equals("h")) {
          System.out.println("'" + move + "'"+ " is not a valid option.");
          System.out.print("Who should move first? (c=computer h=human): ");
          move =keyboard.nextLine();
          move = move.toLowerCase();
     }
      System.out.print("The computer is X, the human is O");
      if (move.equals("c")) {
          char currentPlayer = 'c';
      } else if (move.equals("h")) {
          char currentPlayer = 'h';
      }

    char currentPlayer = ' ';

此方法询问用户谁应该先玩(井字游戏),然后他们输入“c”或“h”来先玩。如果输入了其他任何内容,那么它将循环直到输入其中一个字符。我上面有其他代码在另一个方法中询问他们是否想玩游戏,这会影响这个方法吗?

示例:

欢迎来到井字游戏!

你想玩游戏吗? (输入“y”表示是或输入“n”表示否):y

谁应该先行动? (c=computer h=human): '' 不是一个有效的选项。 这就是问题所在

谁应该先行动? (c=计算机 h=人类):c

计算机是X,人是O

【问题讨论】:

  • 是的,较早的输入可能会导致此行为(取决于您如何称呼它;您没有在问题中显示该代码)。见here
  • 您是在问我们一些您没有向我们展示的方法可能会产生什么影响?我认为这可能是 clairvoyance.stackexchange.com 的主题。
  • 话虽如此,你的问题可能是当你问他们是否想玩游戏时,你使用的是keyboard.next(),而不是keyboard.nextLine()。调用keyboard.next() 不会消耗行尾的换行符,这意味着下面对keyboard.nextLine() 的调用会返回一个空字符串。
  • @0x5453 我在它之前添加了方法
  • @DawoodibnKareem 是的,就是这样。谢谢

标签: java


【解决方案1】:

这可能是因为您在他们输入任何内容之前进行了检查。所以

“”(空字符串)!=“c”或“h”

然后您会收到错误消息。

【讨论】:

  • 答案应该可以解决手头的问题。另外,请编码格式化
猜你喜欢
  • 1970-01-01
  • 2016-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-12
  • 1970-01-01
  • 2016-07-31
相关资源
最近更新 更多