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

3. (a) Write a toString method for PairOfInts that returns a String expressions

ID: 3773381 • Letter: 3

Question

3. (a) Write a toString method for PairOfInts that returns a String expressions containing the values taken on by the two instance variables of the calling object. The string expression should have the String text and sandwiched between the display of the two int values.

(b). Write the code exchange, a mutator method of PairOfInts that switches between the values between the two instance variable of the calling object. With the following code, the respective three lines of display will be 2 and 6, 6 and 2, 2 and 6.

Explanation / Answer

public class PairOfInts
{
   int a;
   int b;
   public PairOfInts(int a, int b)
   {
       this.a = a;
       this.b = b;
   }
  
   public PairOfInts(PairOfInts d)
   {
       this.a=d.a;
       this.b=d.b;
   }
   //Part A
   public String toString()
   {
       return "The Value of A = "+a+" and B = "+b;
   }
   //Part B
   public void exchange()
   {
       int temp;
      
       for(int i=0;i<3;i++)
       {
           temp=a;
           a=b;
           b=temp;
           System.out.println(toString());
       }
      
   }
   public static void main(String args[])
   {
       PairOfInts pairD = new PairOfInts(7,9);
       PairOfInts pairE = new PairOfInts(pairD);
       pairD.exchange();
       pairE.exchange();
       if(pairD.equals(pairE))
       System.out.println("pairD and pairE are equal to each other");
   }
  
}

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