Write a method named hasMidpoint that accepts three integers as parameters and returns true if one of the integers is the midpoint between the other two integers; that is, if one integer is exactly halfway between them. Your method should return false if no such midpoint relationship exists. For example, the call hasMidpoint(7, 4,10) should return true because 7 is halfway between 4 and 10. By contrast, the call hasMidpoint(9, 15, 8) should return false because no integer is halfway between the other two. The integers could be passed in any order;
the midpoint could be the 1st, 2nd, or 3rd. You must check all cases. If your method is passed three of the same value, return true.
// package indefinite_loops; import java.util.Arrays; public class HasMidPoint { public boolean hasMidPoint(int a, int b, int c) { // push these vales in an array int numbers[] = new int[3]; numbers[0] = a; numbers[1] = b; numbers[2] = c; // sort them Arrays.sort(numbers); boolean flag = true; int diff = numbers[1]-numbers[0]; // compare them through loop if their difference is constant for (int i = 1; i < numbers.length; i++) { if (numbers[i] != numbers[i - 1] + diff) { flag = false; } } return flag; } public static void main(String[] args) { HasMidPoint has = new HasMidPoint(); // call the method boolean hasMidPoint = has.hasMidPoint(8, 15, 9); System.out.println("does one of the value is midpoit? : " +hasMidPoint); } }
Output:
does one of the value is midpoit? : false