0
如果你運行遊戲,你可以看到遊戲無法正確猜測的某些數字。例如,如果你的數字是13,那麼遊戲會循環太多次,也會猜測你的數字是12而不是13。我認爲這是一個計數問題,但我已經試過重複追蹤循環,但是找不到錯誤。我認爲這個問題主要在於我的while循環。數猜猜遊戲不斷重複相同的問題,並猜測不正確
//import statements
import java.util.Scanner;
public class Numbers
{
public static void binarySearch()
{
int position=0;
String answer;
int upper_BOUND=100;
int lower_BOUND=0;
Scanner input=new Scanner(System.in);
while((lower_BOUND <= upper_BOUND))
{
position = (lower_BOUND + upper_BOUND)/2;
System.out.println("Is your value greater than " + position + "?");
answer=input.next();
if((upper_BOUND-lower_BOUND<=1))
{
break;
}
if (answer.equals("no")) // If the number is > key, ..
{ // decrease position by one.
upper_BOUND = position --;
}
if(answer.equals("yes"))
{
lower_BOUND = position ++; // Else, increase position by one.
}
}
System.out.println("Is your number " + position + "?");
String answer2=input.next();
System.out.println(position+" is the answer.\n Thank you for playing the guessing game.");
//else
// System.out.println("Bruh pick a number from 1 to 100 ");
}
}
...... 測試類
public class NumberGuesser
{
public static void main(String[] args)
{
int[ ] num = new int [100];
// Fill array
for (int i = 0; i <= 99; i++)
num[i]=i;
//The search method
Numbers.binarySearch();
}
}
有什麼問題。 – Abhishek 2015-04-03 09:11:22
您在NumberGuesser類中創建了數組,但是您沒有在任何地方使用:D然後在哪裏搜索? – Prashant 2015-04-03 09:13:35