Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider the following contract specification for the static method average. Ple

ID: 3781619 • Letter: C

Question

Consider the following contract specification for the static method average. Please note that, both in the specification and in the Java programming language, the integer-division ('/') operator's result is obtained by truncating toward zero. Hence. (-3/2) = -1 and (9/2) = 4. It is like "rounding", except that the quotient given as the result is not necessarily the closest integer to the correct rational quotient: it is the first-encountered integer closer to zero than the correct rational quotient. Returns the integer average of two given {@code int}s. @param j the first of two integers to average @param k the second of two integers to average @return the integer average of j and k @ensures average = (j+k)/2/public static int average (int j, int k) {...} Answer the following questions. Provide an argument justifying the following claim: The average (as defined here) of two Java ints i and j is representable as an int. regardless of the lower and upper bounds on the value of an int. Provide an implementation of the average method with int as the only type you use (except, perhaps, for boolean).

Explanation / Answer

a) Yes, thats right because both i and j are ints, the average will result in taking the quotient only after the operation is done.

Here is an example,

public static int Average(int i, int j)
   {
       return (i+j)/2;
   }
   public static void main (String[] args) throws java.lang.Exception
   {
       System.out.println(Average(4,3));
   // The output here is 3.
   }

b) The following code works for all the integer values,

public static int Average(int i, int j)
   {
       if(i%2 != 0 && j%2 != 0)
           return i/2+j/2+1;
       else return i/2+j/2;
   }
   public static void main (String[] args) throws java.lang.Exception
   {
       System.out.println(Average(Integer.MAX_VALUE,Integer.MAX_VALUE));
       System.out.println(Average(8,5));
       System.out.println(Average(7,7));
   }

OUTPUT:

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote