0

This is a simple program that generates two random numbers between 0 and 1000, then has the user enter the sum of the two numbers. The if statement always evaluates as incorrect though even if you input the correct answer and sum and answer match.

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

public class mathquiz
{
    public static void main(String[] args)
    {
        Integer num1;
        Integer num2;
        Integer sum;
        Integer answer;
        Scanner input = new Scanner(System.in);
        Random rand = new Random();
        num1 = rand.nextInt(1000); //random number between 0 and 1000
        rand = new Random();
        num2 = rand.nextInt(1000); //random number between 0 and 1000
        System.out.println("  "+num1); 
        System.out.println("+ "+num2);
        sum = num1 + num2; //adding the two random numbers together
        answer = input.nextInt();
        System.out.println(sum); //test print to see what sum is
        System.out.println(answer); //test print to see what answer is
        if (sum == answer) //always evaluates as incorrect, I would like to know why
        System.out.println("Congratulations! You are correct!");
        else
        System.out.println("You were incorrect. The correct answer is: "+sum);
    }
}

4 Answers4

1

The problem is that you're using the Integer wrapper class instead of an int primitive, but you're using identity (==) instead of object equality (equals) to compare. Change all your Integers to ints.

Note that for small integers, this will actually work because of an optimization that caches Integer objects for small values, but it's still a bug.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
0

sum.equals(answer) might give you the result you want.

Patrick vD
  • 684
  • 1
  • 7
  • 24
0

The problem you are having is because you are comparing one oject with another object to see if they are the same object, which they are not.

try either compare primitive value using the intValue() method or use the equals method.

if (sum.intValue () == answer.intValue ()) 
{
  ....
}

or

 if (sum.equals (answer))
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

== is a comparison of reference, while .equals() is a comparison of values

.equals() could be thought of as "meaningfully equivalent" whereas == generally means "literally equivalent"

Try if (sum.equals(answer))

Chris Carr
  • 25
  • 4