开发者

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;
    开发者_JAVA百科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..");
    }
}


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.


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.


You're calculating min and max based on guess, so guess is always between min and max so (guess > min) && (guess < max) is always 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");
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜