2016-02-24 66 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