Write a static method named hasMidpoint that accepts three integers as parameter
ID: 3645443 • Letter: W
Question
Write a static method named hasMidpoint that accepts three integers as parameters andreturns 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. The integers could be passed in any order; the midpoint
could be the 1st, 2nd, or 3rd. You must check all cases.
Calls such as the following should return true :
hasMidpoint(4, 6, 8)
hasMidpoint(2, 10, 6)
hasMidpoint(8, 8, 8)
hasMidpoint(25, 10, -5)
Calls such as the following should return false :
hasMidpoint(3, 1, 3)
hasMidpoint(1, 3, 1)
hasMidpoint(21, 9, 58)
hasMidpoint(2, 8, 16)
Explanation / Answer
public class MidPoint{
public static boolean hasMidpoint(int a, int b ,int c ){
int left,right,mid;
int [] ar = new int[3]; // create a three element array
ar[0] = a;ar[1]=b;ar[2]=c; // put a, b ,c into it
left = findMinInd(ar,3); // find index of min element
right = findMaxInd(ar,3); // find index of largest element
int thirdIndex = findThirdIndex(ar,left,right,3); //find index of remaining element
mid =( ar[left] + ar[right] )/2; // compute mid point
System.out.println(left + ":" + thirdIndex + ":" + right);
if ( ar[thirdIndex] == mid ) // if equal return true else return false
return true;
else
return false;
}
static int findMinInd(int ar[],int size ){ // find index of min elem
int min=999999;
int ind = 0;
for ( int i = 0 ;i<size;i++){
if (ar[i] < min ){
min = ar[i];
ind = i;
}
}
return ind;
}
static int findMaxInd(int ar[],int size ){ // find index of max eleme
int max=-999999;
int ind = 0;
for ( int i = 0 ;i<size;i++){
if (ar[i] >= max ){
max = ar[i];
ind = i;
}
}
return ind;
}
public static void main(String args[]){
System.out.println(hasMidpoint(4, 6, 8) );
System.out.println(hasMidpoint(4, 3, 8) );
System.out.println(hasMidpoint(1, 6, 8) );
System.out.println(hasMidpoint(1, 3, 1) );
System.out.println(hasMidpoint(3, 1, 3) );
System.out.println(hasMidpoint(2, 10, 6) );
System.out.println(hasMidpoint(8, 8, 8) );
System.out.println(hasMidpoint(25, 10, -5) );
}
public static int findThirdIndex(int ar[],int left,int right,int size){ // find index of rem elem
int ind = -1;
for ( int i = 0;i < size;i++){
if ( i == left || i == right )
continue;
else
ind = i;
}
return ind;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.