计算有多少低和高的猜测

时间:2015-03-08 18:17:21

标签: java

我需要计算有多少猜测太高,有多少太低。然后在用户最终猜对时打印这些值以及猜测总数。

你能否告诉我如何修改我的程序来计算高估值?

主要代码

public class Task4t2 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        boolean win = false;
        boolean running = true;
        System.out.println("Please enter the upper limit: ");
        Game game = new Game(scan.nextInt());

        while (running) {

            System.out.println("Please enter a guess ");

            while (!win) {
                if (game.guess(scan.nextInt())) {
                    win = true;
                }
            }
            System.out.println("Would you like to play again y/n?");
            String playAgain = scan.next();
            if (playAgain.equalsIgnoreCase("y")) {
                game.reset();
                running = true;
                win = false;
            } else {
                running = false;
                System.out.println("Game over");
            }
        }
    }
}

在此处输入代码:

import java.util.Random;

public class Game {

    private int randomNumber;
    private int tries = 0;
    private int range;

    public Game(int range) {
        this.range = range;
        generateRandomNumber();
    }

    private void generateRandomNumber() {
        Random rand = new Random();
        this.randomNumber = rand.nextInt(range) + 1;
    }

    public boolean guess(int guess) {
        tries++;
        if (guess == randomNumber) {
            if (tries > 1) {
                System.out.println("You got the number in " + tries + " tries.");
                return true;
            } else {
                System.out.println("You got the number in " + tries + " try.");
                return true;
            }
        } else if (guess > randomNumber) {
            System.out.println("Too high try again");
            return false;
        } else if (guess < randomNumber) {
            System.out.println("Too low try again ");
            return false;
        }
        return false;

    }

    public void reset() {
        this.tries = 0;
        generateRandomNumber();

    }

}

1 个答案:

答案 0 :(得分:-1)

ArrayList<Integer> High = new ArrayList<Integer>();
ArrayList<Integer> Low = new ArrayList<Integer>();
while (!win){    //numbers is your array
    int x = scan.nextInt();
    if (game.guess(x))
        win = true;
    else if ( x > desired) //where desired is the random integer
       High.add(x);
    else 
       Low.add(x);
}
for (int x : High)
     System.out.println(x);
for (int x : Low)
     System.out.println(x);

如果您打算稍后使用,则应存储扫描。保持数字使用动态数组。你不知道这个人会猜多少个数字。我推荐两个ArrayList。一个用于存储太高的数字,另一个用于存储太低的数字。然后你可以用一般的for循环或者我在下面使用的那个打印它们。