Java 如何将这个Do While循环转换为另一种循环,While循环?
这就是整个方法,我唯一想解决的就是这个Java 如何将这个Do While循环转换为另一种循环,While循环?,java,loops,methods,while-loop,do-while,Java,Loops,Methods,While Loop,Do While,这就是整个方法,我唯一想解决的就是这个 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); Sys
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();
}
它必须多次接受输入,因此每次都需要输入来确定发生了什么,这就是为什么我喜欢Do-While循环,但由于它每次至少初始化一次,所以我得到了比需要更多的滚动
我曾尝试过这样做,以及这种方式的各种变体:
String eitherOr;
do {
eitherOr= input.nextLine();
humanRoll();
} while (eitherOr.isEmpty());
这不起作用,因为它不会再次请求输入。如果我尝试将input.nextline()放入;在while循环中,它表示“eitherOr”未初始化,即使我在输入input时对其进行初始化,命令行仍然为空,因此它对我的输入不起任何作用。您得到了一个无关的分号:
String eitherOr = input.nextLine();
while(eitherOr.isEmpty());
humanRoll();
应该是:
while(eitherOr.isEmpty());
humanRoll();'
本质上,你的版本是说什么都不做,而
eitherOr.isEmpty()
是true
,因此它永远不会调用humanRoll
,你有一个无关的分号:
String eitherOr = input.nextLine();
while(eitherOr.isEmpty());
humanRoll();
应该是:
while(eitherOr.isEmpty());
humanRoll();'
本质上,您的版本是在
eitherOr.isEmpty()
为true
时说什么都不做,因此,如果您的第二个代码段作为while循环的一部分执行空白语句,它永远不会调用humanRoll
while(eitherOr.isEmpty())
humanRoll();
为了将humanRoll作为循环的一部分执行,必须删除此分号
while(eitherOr.isEmpty());//this semicolon is a blank statement
humanRoll();
另一方面,使用偏执通常可以避免这样的小问题
while(eitherOr.isEmpty())
humanRoll();
在上面的代码中,很容易识别是否引入了无意中的分号。如果您的第二个代码段,您将执行空白语句作为while循环的一部分
while(eitherOr.isEmpty())
humanRoll();
为了将humanRoll作为循环的一部分执行,必须删除此分号
while(eitherOr.isEmpty());//this semicolon is a blank statement
humanRoll();
另一方面,使用偏执通常可以避免这样的小问题
while(eitherOr.isEmpty())
humanRoll();
在上面的代码中,很容易识别是否无意中引入了分号。那么,似乎在分号上浪费了最后一个小时。谢谢,我已经有一段时间没有使用while循环了。由于这次不幸,我预计我会重读几章。老实说,可能应该是我检查的第一件事。@LanceySnr代码仍然像在do while循环中一样工作,即使有输入,它仍然会创建另一个卷。有输入时,您是否使用调试器或类似工具检查它的内容?考虑到发布的代码,我看不出它是如何执行循环的。那么,最后一个小时似乎浪费在了分号上。谢谢,我已经有一段时间没有使用while循环了。由于这次不幸,我预计我会重读几章。老实说,可能应该是我检查的第一件事。@LanceySnr代码仍然像在do while循环中一样工作,即使有输入,它仍然会创建另一个卷。有输入时,您是否使用调试器或类似工具检查它的内容?鉴于发布的代码,我看不出它如何执行循环。