这只是我所参加的Comp Sci简介课程的一个小作业,但我遇到了一些麻烦,我必须提示用户验证代码所做的猜测,然后是#&#如果它更高或更低等等,它会提示错误。我想这样做,如果最大数字范围是12,我会从6开始,从那里我会问用户:如果它是正确的?如果没有,那么问问它是高还是低。根据他的回答,我的下一个值将介于0和6之间,即3或6和12,即9。我尝试了多种不同的方式,并在网上搜索了一些提示,但没有运气。如果你可以帮我解决我的代码,或者可以指导我找到一个很棒的答案!
Scanner in = new Scanner(System.in);
boolean guess = false;
int maxMonth = 12;
int minMonth = 0;
int month = (maxMonth - minMonth) / 2;
int total = 6;
while (guess == false) {
String yes = "yes";
String no = "no";
int tries = 0;
boolean firstGuess = false;
System.out.println("Is your birthday in " + month + " yes or no:");
String a1 = in.next();
if (a1.equals(yes)) {
firstGuess = true;
} else {
System.out.println("Is your birthday after this month?");
String a2 = in.next();
if (a2.equals(yes)) {
total++;
total = (int) total / 2;
month = month + total;
} else {
total = total - 3;
total = (int) total / 2;
month = month + total;
}
}
//guesses the day in the month
while (firstGuess == true) { }
}
答案 0 :(得分:0)
您需要计算循环内月份的值。每次猜测后,如果a2为是,则更新minMonth = month + 1,如果a2如果没有更新maxMonth = month - 1,则再次循环(重新计算month =(maxMonth - minMonth)/ 2)。
你的循环的条件是而(guess == false)但是你永远不会改变guess的值,所以你永远不能退出循环。你需要 if(a1.equals(yes))guess = true; (不是firstGuess)。