Cmputer不遵守规则

时间:2016-02-24 07:36:03

标签: java

我正试图想出一个反向猜谜游戏。计算机猜测我选择的数字,范围为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.

2 个答案:

答案 0 :(得分:0)

你应该尝试接近你的猜测。你应该尝试嵌套的间隔。你的班级是随机工作的,当然你的计算机可以再次猜测另一个高数字,只需将范围降低一个。

你应该使用至少2个新变量rangeLow和rangeHigh。从什么时候开始,你的新范围是你的最后一次猜测。什么时候低,你的新范围低,这是你的最后一次猜测。

computerGuess = value.nextInt(rangeLow,rangeHigh);

答案 1 :(得分: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.");
    }
}