1
public void humanPlay()
 {
if (player1.equalsIgnoreCase("human"))
    System.out.println("It is player 1's turn.");
else
    System.out.println("It is player 2's turn.");

System.out.println("Player 1 score: " + player1Score);
System.out.print("Player 2 score: " + player2Score);

String eitherOr;

  do {
    eitherOr= input.nextLine(); 
    humanRoll();
  } while (eitherOr.isEmpty());

 if (!eitherOr.isEmpty())
    humanHold();

}

这是整个方法,我唯一要解决的就是这个。

       String eitherOr;
do {
     eitherOr= input.nextLine();    
     humanRoll();
   } while (eitherOr.isEmpty());

它必须多次接受输入,因此每次都需要输入来确定会发生什么,这就是我喜欢 Do While 循环的原因,但由于它每次至少初始化一次,所以我得到了比需要的额外滚动。

我试图这样做,以及这种方式的各种变体:

String eitherOr = input.nextLine();

while(eitherOr.isEmpty());
        humanRoll();

这不起作用,因为它不会再次要求输入。如果我尝试输入 input.nextline(); 进入while循环,它说“eitherOr”没有初始化,即使我在输入输入时初始化它,命令行保持空白,所以它对我的输入没有任何作用。

4

2 回答 2

4

你有一个无关的分号:

while(eitherOr.isEmpty());
    humanRoll();'

应该:

while(eitherOr.isEmpty())
    humanRoll();

本质上,您的版本是在说什么都不做eitherOr.isEmpty()true所以它永远不会调用humanRoll

于 2011-12-12T04:15:03.970 回答
1

如果您的第二个代码片段正在执行一个空白语句作为您的 while 循环的一部分

while(eitherOr.isEmpty());//this semicolon is a blank statement
    humanRoll();

您必须删除此分号才能将 humanRoll 作为循环的一部分执行

while(eitherOr.isEmpty())
    humanRoll();

附带说明一下,使用括号通常可以避免这样的小问题

while(eitherOr.isEmpty()) {
    humanRoll();
}

在上面的代码中,很容易识别是否引入了无意的分号。

于 2011-12-12T04:22:22.760 回答