2016-02-24 102 views
-2

我正試圖想出一個反向猜測遊戲。電腦猜測我選擇的數字範圍爲1-100。我有二進制搜索算法,但是當我告訴計算機它首先猜測是太高時,它會給我另一個高估,而不是降低。沒有遵守規則的計算機

import java.util.Random; 
import java.util.Scanner; 

public class ComputersGuessGame { 

public static void main(String[] args) { 

    Scanner in = new Scanner(System.in); 
    Random value = new Random(); 

    int computerGuess; 
    int highValue = 100; 
    int lowValue = 1; 
    String myAnswer; 

    do { 
     computerGuess = value.nextInt(highValue - lowValue +1)/2; 

     /* 
     *Above line should use the binary algorithm so the computer can 
     *make guesses and not just guess my number by going one number at a time 
     */ 

     System.out.println("I'm guessing that your number is " + computerGuess); 
     myAnswer = in.nextLine(); 


     if (myAnswer.equals("tl")){ 
      highValue = computerGuess + 1;//Too Low Answer 
     } 
     else if (myAnswer.equals ("th")){ 
      lowValue = computerGuess - 1;//To High Answer 
     } 
    } while (!myAnswer.equals("y")); //Answer is correct 

    in.close(); 
    System.out.println("Thank you, Good Game."); 


     } 
}//Comptuer keeps making random guesses, but if I say too high, it will guess another high number instead of going low. 
+0

的工作解決方案,如果我選擇20和電腦猜90.然後是太高。那麼'lowValue'將是89.這意味着生成的下一個隨機數將在範圍內(1,6)...似乎是正確的 – Idos

+0

您能舉出一個完整的輸入/輸出示例嗎? – Idos

+0

我仍在搜索二進制搜索。索莫妮找到了嗎? – Prashant

回答

0

我想你的邏輯猜測下一個數字是錯誤的。您應該將設置較低的設置更改爲較高值,並更改邏輯以生成下一個猜測。

這裏是你的問題

import java.util.Random; 
import java.util.Scanner; 

public class Guess { 
    public static void main(String[] args) { 
     Scanner in = new Scanner(System.in); 
     Random value = new Random(); 
     int computerGuess; 
     int highValue = 100; 
     int lowValue = 1; 
     String myAnswer; 
     do { 
      computerGuess = value.nextInt(highValue - lowValue)+lowValue; 
      System.out.println("I'm guessing that your number is " + computerGuess); 
      myAnswer = in.nextLine(); 
      if (myAnswer.equals("tl")){ 
       lowValue = computerGuess + 1; 
      } else if (myAnswer.equals ("th")){ 
       highValue = computerGuess - 1; 
      } 
     } while (!myAnswer.equals("y")); 
     in.close(); 
     System.out.println("Thank you, Good Game."); 
    } 
} 
+0

感謝您的反饋Taj – neme0025

+0

我的寶貴幫助 –

0

你應該儘量接近你的猜測。你應該嘗試嵌套的時間間隔。你隨機使用課程,當然你的計算機可以再次猜測另一個高數字,當只降低一個範圍時。

您應該至少使用2個新變量rangeLow和rangeHigh。什麼時候到高點,你的新射程是你最後的猜測。什麼時候低,你的新rangeLow是你最後的猜測。

computerGuess = value.nextInt(rangeLow,rangeHigh);

+0

感謝bloodscript和Taj Ahmed的反饋。當一個小角色不合時宜時,這很有趣也很沮喪。第二雙眼睛正是我所需要的。 – neme0025