我的代码是猜谜游戏。当用户用尽猜测或猜测幻数时,我应该问他们是否想要再次猜测一个数字。只要用户没有进入哨兵就应该能够运行1000次,这就是"没有。"我需要让我的代码循环到它将继续前进的位置,直到用户说出#34; no。"
我试图在我的代码底部执行此操作,但因为我觉得我应该在开始时做一些事情使它成为一个循环而陷入困境...有人可以告诉我应该如何包含这个在我的代码中?
答案 0 :(得分:2)
您需要按照以下说明运行循环:
final String SENTINEL = "no";
# put your required code here
System.out.print(" Would you like to try to guess a number? (Yes or No):");
String answer = scan.next();
while(!answer.equals(SENTINEL)){
# put your required code here
# do all your stuff and then ask users' preference again
System.out.print("Would you like to try to guess a number? (Yes or No):");
answer = scan.next();
}
您还可以使用 do-while 循环,以更好地满足您的需求。
final String SENTINEL = "no";
# put your required code here
System.out.print(" Please enter your name: ");
String name = scan.next();
do{
# put your required code here
# do all your stuff and at the end of the loop ask users' preference
System.out.print("Would you like to try to guess a number? (Yes or No):");
String answer = scan.next();
}while(!answer.equals(SENTINEL));
do-while 和 之间的区别在于do-while在循环底部而不是顶部评估其表达式。因此,执行块中的语句总是至少执行一次。