-2

I used random generator to generate four numbers, then I have to decide if three of them are the same.

What is wrong with the following code ?

if((r1= r2 =r3)|| (r1 = r2 = r4)|| (r1 = r3 =r4)|| (r2 = r3 =r4)) {
    System.out.println("Three of a kind.");
}

The error says cannot convert from int to boolean. Also, I thought it should be ==, but == yields error while = doesn't.

dumbPotato21
  • 5,669
  • 5
  • 21
  • 34
  • 2
    `r1 = r2 = r3` makes `r1` and `r2` equal to `r3`. The comparison should run more like `r1 == r2 && r1 == r3` .. because that would mean `r2 == r3` by extension – MadProgrammer Jan 23 '17 at 04:46
  • Possible duplicate of [In java equal and == behaviour](http://stackoverflow.com/questions/26081037/in-java-equal-and-behaviour) – ravthiru Jan 23 '17 at 04:48
  • nope, not a duplicate (of the previous comment) – alexbt Jan 23 '17 at 04:49
  • 2
    Besides: consider using an array here to hold the values, instead of 4 distinct variables... As that makes your solution really hard to enhance. – GhostCat Jan 23 '17 at 04:50
  • "but == yields error while = doesn't" -- didn't you just say that you get an error "cannot convert `int` to `boolean` with `=` ?? – Erwin Bolwidt Jan 23 '17 at 05:16

1 Answers1

1

You need to use the equality operator ==, not the assignment operator =.

When you compare integers you do it like this:

if(int1 == int2) {
    // they are equal
}

If you want to test that 3 integers are equal, you could do it like this:

if(int1 == int2 && int2 == int3) {
    // all three integers are equal
}

See that we have used the logical AND operator && to combine two boolean expressions so that both expressions must be equal for the if statement to evaluate to true.

Matt
  • 3,677
  • 1
  • 14
  • 24