简体   繁体   中英

What's wrong with my logic (Java syntax)

I'm trying to make a simple program that picks a random number and takes input from the user. The program should tell the user if the guess was hot (-/+ 5 units) or cold, but I never reach the else condition.

Here's the section of code:

    public static void giveHint (int guess) {
    int min = guess - 5;
    int max = guess + 5;
    if ((guess > min) && (guess < max)) {
        System.out.println("Hot..");
    } else {
        System.out.println("Cold..");
    }
}
int min = guess - 5;
int max = guess + 5;

Should be:

int min = actualAnswer - 5;
int max = actualAnswer + 5;

Here is your problem:

int min = guess - 5;
int max = guess + 5;

min is ALWAYS lesser than guess and max is ALWAYS greater than guess .

You need to pass in the actual answer, not just the guess, since the logic can't tell what the appropriate mix/max should be otherwise:

public static void giveHint (int guess, int actual) {
    int min = actual - 5;
    int max = actual + 5;
    if ((guess > min) && (guess < max)) {
        System.out.println("Hot..");
    } else {
        System.out.println("Cold..");
    }
}

You are defining guess as being both > min (because int min = guess - 1 ) and < max (because int max = guess + 5 ). So of course the first condition is always met. You should be using the actual secret value when defining min and max .

min and max should use the value the player is looking for (secret value) rather than the value the player provided. As it is, min and max change every time the player gives a guess and you're not even using the secret value.

您是根据猜测来计算最小值和最大值,因此猜测始终在最小值和最大值之间,因此(guess> min)&&(guess <max)始终为true。

Lets use an example:

int guess = 20;
int min = guess - 5 = 15;
int max = guess + 5 = 25;

therefore

min < guess < max

Why?

Because you're comparing guess to its self! I think you need to have the actual answer, not the guess

I can't put the full thing in a comment, so here's what your code should be:

    public static void giveHint (int guess, int actual) {
    int min = actual - 5;
    int max = actual + 5;
    if ((guess > min) && (guess < max)) {
        System.out.println("Hot..");
    } else {
        System.out.println("Cold..");
    }

Another solution :

    public static void giveHint (int actual, int guess) {
         if(Math.abs(actual - guess) <= 5) {
             System.out.println("Hot");
             return;
         }

         System.out.println("Cold");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM