-1

this code is supposed to have you pick a # then by telling the pc is its to low or too high you lower the range of the pc's guess but the range does not seem to change could someone help `enter code here.:

int min = 1;
int max = 100;
Scanner i = new Scanner(System.in);
System.out.println("whats the number");
int ans = i.nextInt();
int guess = (int)(Math.random()* 100 + 1);
while(ans != guess)
{
    System.out.println(guess);
    System.out.println("is that number to high)1 or to low)2");
    int p = i.nextInt();
    if(p == 1)
    {
        if(guess < max)
        {
            max = guess;
            guess = (int)(Math.random()*max + min); 
        }
        else
        {
            guess = (int)(Math.random()*max + min);
        }
    }
    if(p == 2)
    {
        if(guess > min)
        {
            min = guess;
            guess = (int)(Math.random()*max + min); 
        }
        else
        {
            guess = (int)(Math.random()*max + min);
        }
    }
}
System.out.println(guess + " is right");

1 Answers1

0

I think you have to change your guess variable calculation method.

You want to guess number which is between min and max. So you can use this strategy.

guess = rand.nextInt((max - min) + 1) + min;

Below you can find full code:

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

public class NumbersTest {

    public static void main(String[] args) {

        int min = 1;
        int max = 101;
        Scanner i = new Scanner(System.in);
        System.out.println("whats the number");
        int ans = i.nextInt();
        Random rand = new Random(); //NOTE
        int guess = rand.nextInt((max - min) + 1) + min; //NOTE
        while (ans != guess) {
            System.out.println(guess);
            System.out.println("is that number to high)1 or to low)2");
            int p = i.nextInt();
            if (p == 1) {
                if (guess < max) {
                    max = guess;
                    guess = rand.nextInt((max - min) + 1) + min; //NOTE
                } else {
                    guess = rand.nextInt((max - min) + 1) + min; //NOTE
                }
            }
            if (p == 2) {
                if (guess > min) {
                    min = guess;
                    guess = rand.nextInt((max - min) + 1) + min; //NOTE
                } else {
                    guess = rand.nextInt((max - min) + 1) + min; //NOTE
                }
            }
        }
        System.out.println(guess + " is right");
    }
}
Community
  • 1
  • 1
CrazyJavaLearner
  • 368
  • 8
  • 17