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

Consider the following class: public class Fraction implements Comparable{ publi

ID: 3728448 • Letter: C

Question

Consider the following class:

   public class Fraction implements Comparable{

       public int getNum() {

           return num;

       }

       public int getDenom(){

           return denom;

       }

       public double doubleValue(){

           return (double)num / denom;

       }

       < Other constructors and methods not shown >

       private int num, denom;

   }

Which of the following would appropriately implement a compareTo method, required by the Comparable interface?

I   public int compareTo(Fraction other){

       return getNum() * other.getDenom() –

           getDenom() * other.getNum();

   }

II   public int compareTo(Object other){

       double x = doubleValue();

       double y = ((Fraction)other).doubleValue();

       if (x < y) return –1;

       else if (x > y) return 1;

       else return 0;

   }

III   public int compareTo(Object other){

       return (int)(doubleValue() –

((Fraction)other).doubleValue());

   }

(A)   I only

(B)   II only

(C)   I and II only

(D)   II and III only

(E)   I, II, and III

Explanation / Answer

answer : B

explanation:

II only calculate the double value ,

double x = doubleValue(); =>division value of num/denom

double y = ((Fraction)other).doubleValue();  =>divison value of other, num/denom

and if (x < y) , x less than y returns -1 value

if (x > y) , x greater than y returns 1.

if both equal return 0;

while other two option just returns the difference between the two fraction,

//for any clarification, please do comments

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