Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!

# How to use boolean statements to return "true" for certain cases?

Ashley Kin
Ranch Hand
Posts: 36
Hello, I'm trying to write a method that will accept three integers as parameters and return true if one of the integers is the midpoint between the other two integers, and order does not matter. I'd appreciate some help on how I should use boolean statements in this; would I just have an if/else statement for each possible situation?
ie. if((a+b)/2 = c) and then if ((b+c)/2 = a) and so forth, having each print "true" if it is true? Any help is appreciated, thanks!

my main method calls it like this: isMidpoint(2, 8, 5) <= that would return as true

Ralph Cook
Ranch Hand
Posts: 479
Although you could have separate if statements for each case, it seems a bit messy.

If you say what you want in English, it would have 2 ORs in it -- each integer might be the midpoint, the others are added and so order does not matter to their sum, so you have three situations: (a+b)/2 = c, (a+c)/2 = b, (b+c)/2 = a. So use each of those expressions separated by Java's OR operator:

I like to format my complex condition clauses to line up beginning and ending parentheses where they might be missed; that's just a matter of style.

Another matter of style: you don't need an if statement at all. The entire expression in parens is a boolean expression; you can just return it:

A version using an if statement is going to be easier to debug, but it's good to know this coding pattern because you will see it in other's code.

Campbell Ritchie
Sheriff
Posts: 48394
56
You need to check you are using the equality operator == not the assignment operator =. You should use the second version as better style. Also, work out the expression with pencil and paper before trying to code it.

Ove LindstrÃ¶m
Ranch Hand
Posts: 326
Campbell Ritchie wrote:... Also, work out the expression with pencil and paper before trying to code it.

The pen is mightier than the compiler... ;)

Campbell Ritchie
Sheriff
Posts: 48394
56
Pencil, pencil, pencil . . .

. . . and a very large eraser, so you can destroy the evidence when you get it wrong

Harsha Smith
Ranch Hand
Posts: 287
And Sharpner?

Matthew Brown
Bartender
Posts: 4565
8
One other thing you're going to have to watch out for is integer arithmetic. With the examples above, if the input is 1, 2, 4, that's going to return true, because (1+4)/2 will evaluate to 2 because of the truncation. Which probably isn't what you want.

A simple approach to fixing this would be to double all the values first! Or (equivalently) compare 2*(a + b) == c, instead.

Ralph Cook
Ranch Hand
Posts: 479
Campbell Ritchie wrote:Pencil, pencil, pencil . . .

. . . and a very large eraser, so you can destroy the evidence when you get it wrong

And extra equals signs, in case you forget them... 8<(

rc