SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Program Logic And Indefinite Loops
Exercise:
Exercises
Question:15 | ISBN:9780136091813 | Edition: 2

Question

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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

// 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

 

0 0

Discussions

Post the discussion to improve the above solution.