所以我做了這個遊戲,我選擇了一個隨機數字1-100,並且計算機猜測,我告訴它太高,太低或者其他。它工作得很好,除了當我嘗試二進制搜索時陷入循環,而我似乎無法阻止它。我將演示:數字猜測遊戲不斷重複?
說這個數字是79.最終,程序會詢問數字是否爲42.不,那太低了。然後它會問是否71.猜測更高!然後它問82.不,降低。然後它回到42,循環重複一遍又一遍。這裏是我的代碼(注意,這是從完整代碼的摘錄,所以藉口缺乏的JOptionPane和諸如此類的進口):
int x = 50;
int y = x;
int[] alreadyGuessed = {};
boolean secondGuess = false;
//The user has to select, too high, too low, correct!
while (secondGuess == false) {
Object[] options = {"Too high", "Too Low", "Correct"};
int pick = JOptionPane.showOptionDialog(null, "Is your number " + x
+ "?", "Guess",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
null, options, options[2]);
for (int positionInList = 0; positionInList >= 100; positionInList++) {
arrayDemo(x, positionInList);
}
if (pick == 0) {
int max = x - 1;
int min = 0;
x = ((max + min)/2);
}
if (pick == 1) {
int max = 100;
int min = x+1;
x = ((max + min)/2);
}
if (pick == 2) {
System.out.println("Yay! I win!");
secondGuess = true;
}
}
爲什麼當人選擇「過高」時,將'min'設置爲零?當人選擇「太低」時,爲什麼要將'max'設置爲100?你在哪裏跟蹤'min'和'max'猜測? – 2014-12-13 01:41:06
哎呦,把它弄倒了 – Tim 2014-12-13 01:45:50
如果猜測太低,你應該做的就是把分鐘提高到比猜測更多,對嗎?如果猜測太高,你應該做的就是將最大值降低到小於猜測值,對嗎?爲什麼在每種情況下都改變最小值和最大值? – 2014-12-13 01:47:52