This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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
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.
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.
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.