What's wrong with my logic (Java syntax)

I am trying to create a simple program that picks a random number and takes data from the user. The program should tell the user whether the guess was hot (- / + 5 units) or cold, but I never reach the else clause.

Here's the code section:

    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..");
    }
}

      

+2


a source to share


9 replies


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

      

Should be:



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

      

+11


a source


Here is your problem:

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

      



min

ALWAYS less guess

and max

ALWAYS more than guess

.

+8


a source


You define guess

both > min

(because int min = guess - 1

) and < max

(because int max = guess + 5

). Therefore, of course, the first condition is always met. You must use the actual secret when determining min

and max

.

+1


a source


You need to pass the actual answer, not just a guess, since the logic can't figure out what the corresponding mix / max 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..");
    }
}

      

0


a source


min

and max

must use the value the player is looking for (secret value) and not the value provided by the player. Be that as it may, min

and max

change every time the player makes a guess and you don't even use the secret value.

0


a source


You calculate min and max based on guesswork, so guess is always between min and max so (guess> min) && & & (guess <max) is always true.

-1


a source


Let's use an example:

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

      

so

min < guess < max

      

Why?

Because you are being compared to yourself! I think you want an actual answer, not an assumption

-1


a source


I can't put everything in a comment, so here's what it should be for your code:

    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..");
    }

      

-1


a source


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");
    }

      

-1


a source







All Articles