【问题标题】:How can i convert this Do While loop into another sort of loop, a while loop?如何将此 Do While 循环转换为另一种循环,即 while 循环?
【发布时间】:2012-01-18 04:23:32
【问题描述】:
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”没有初始化,即使我在输入输入时初始化它,命令行也保持空白,所以它对我的输入没有任何作用。

【问题讨论】:

    标签: java loops methods while-loop do-while


    【解决方案1】:

    你有一个多余的分号:

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

    应该是:

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

    基本上你的版本是说当eitherOr.isEmpty()true 时什么都不做,所以它永远不会调用humanRoll

    【讨论】:

    • 那么,似乎最后一个小时被浪费在了一个分号上。谢谢,我有一段时间没有使用while循环了。由于这次不幸,我预见我会重新阅读几章。老实说,可能应该是我检查的第一件事。
    • @LanceySnr 代码仍然像在 do while 循环中一样工作,即使有输入,它仍然会创建另一个滚动。
    • 你有没有使用调试器或类似的工具在有输入时检查它的内容?鉴于发布的代码,我看不出它如何执行循环。
    【解决方案2】:

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

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

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

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

    附带说明,使用括号通常可以避免此类小问题

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

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

    【讨论】:

      猜你喜欢
      • 2015-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-22
      • 1970-01-01
      • 2020-08-28
      • 1970-01-01
      相关资源
      最近更新 更多