tags:

views:

92

answers:

7

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

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.

BalusC
+1 @BalusC : And I would add, that to correct the logic of this function, the `giveHint` method should take in two parameters: `int guess` and `int actual`.
bguiz
@bguiz: yes, @nevelis already pointed that out.
BalusC
I find myself required to state that `min` is less than `guess` (and/)or `max` is greater than `guess`. Consider `guess` as `Integer.MAX_VALUE` and `Integer.MIN_VALUE` for example.
Tom Hawtin - tackline
@Tom: yes, leaving overflows outside consideration for this moment ;)
BalusC
+8  A: 
int min = guess - 5;
int max = guess + 5;

Should be:

int min = actualAnswer - 5;
int max = actualAnswer + 5;
nevelis
+1  A: 

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.

Charles Ma
+1  A: 

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..");
    }
}
Reed Copsey
+1  A: 

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

Yann Ramin
+1  A: 

You are defining guess as being > min (because min = guess - 1) and as being < max (because max = guess + 5).

Phong
+1  A: 

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