Question

In: Computer Science

For these exercises you are required to edit in the Comparable interface implementation, a compareTo() method,...

For these exercises you are required to edit in the Comparable interface implementation, a compareTo() method, starting with the class definition you obtained from the link, and submit that with a client that uses this ordering. If you are so inclined, you may submit a single client to drive your ordering enhancements for both classes, rather than one for each class.

The exercises, for those without the text:

19. Modify the Point class from Chapter 8 so that it defines a natural ordering by implementing the Comparable interface. Compare the Points by y-major order; that is, points with smaller y-coordinate values should come before those with higher y-coordinate values. Break ties by comparing x-coordinate values.

Please include comments, show the output, and put the text code( not just the screenshot of the code)

here are the class to use(Please use them):

1. Point.java

/* * Your file header comment block goes above this line *

* A Point object represents a pair of (x, y) coordinates.

* Class invariant: x >= 0 && y >= 0. (Quadrant I only)

*/

public class Point {

private int x; private int y;

// Constructs a new point at the given (x, y) location. // pre: x >= 0 && y >= 0

public Point(int x, int y) {

if (x < 0 || y < 0) {

throw new IllegalArgumentException();

}

this.x = x; this.y = y;

}

// Constructs a new point at the origin, (0, 0).

public Point() {

this(0, 0);

// calls Point(int, int) constructor

}

// Returns the distance between this Point and (0, 0).

public double distanceFromOrigin() {

return Math.sqrt(x * x + y * y);

}

// Returns whether o refers to a point with the same (x, y)

// coordinates as this point. Robust version.

public boolean equals(Object o) {

if (o instanceof Point) {

Point other = (Point) o;

return this.x == other.getX() && this.y == other.getY();

}

else { // not a Point object return false;

}

}

// Returns the x-coordinate of this point.

public int getX() { return this.x;

}

// Returns the y-coordinate of this point.

public int getY() { return this.y;

}

// Returns a String representation of this point.

public String toString() {

return "(" + this.x + ", " + this.y + ")";

}

// Returns a new point, shifted from this one by dx and dy.

// pre: x + dx >= 0 && y + dy >= 0

public Point translate(int dx, int dy) {

return new Point(this.x + dx, this.y + dy);

}

}

2. PointMainMin.java

/*

* Your file header comment block goes above this line

*

* A client program that deals with simple points.

* Minimal version, to accompany immutable Point class.

*/

public class PointMainMin {

public static void main(String[] args) {

// create two Point objects

Point p1 = new Point(7, 2);

Point p2 = new Point(4, 3);

// print each point and its distance from the origin

System.out.println("p1 is " + p1);

System.out.printf("distance from origin = %3.2f\n", p1.distanceFromOrigin());

System.out.println("p2 is " + p2);

System.out.printf("distance from origin = %3.2f\n", p2.distanceFromOrigin());

}

}

Solutions

Expert Solution

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks

// Point.java


public class Point implements Comparable<Point> {
        private int x;
        private int y;

        // Constructs a new point at the given (x, y) location. // pre: x >= 0 && y
        // >= 0
        public Point(int x, int y) {
                if (x < 0 || y < 0) {
                        throw new IllegalArgumentException();
                }
                this.x = x;
                this.y = y;
        }

        // Constructs a new point at the origin, (0, 0).
        public Point() {
                this(0, 0);
                // calls Point(int, int) constructor
        }

        // Returns the distance between this Point and (0, 0).
        public double distanceFromOrigin() {
                return Math.sqrt(x * x + y * y);
        }

        // Returns whether o refers to a point with the same (x, y)
        // coordinates as this point. Robust version.
        public boolean equals(Object o) {
                if (o instanceof Point) {
                        Point other = (Point) o;
                        return this.x == other.getX() && this.y == other.getY();
                } else { // not a Point object
                        return false;
                }
        }

        // Returns the x-coordinate of this point.
        public int getX() {
                return this.x;
        }

        // Returns the y-coordinate of this point.
        public int getY() {
                return this.y;
        }

        // Returns a String representation of this point.
        public String toString() {
                return "(" + this.x + ", " + this.y + ")";
        }

        // Returns a new point, shifted from this one by dx and dy.
        // pre: x + dx >= 0 && y + dy >= 0
        public Point translate(int dx, int dy) {
                return new Point(this.x + dx, this.y + dy);
        }

        // method to compare two points. returns a negative value if this point is
        // 'less' than p, a positive value if it is 'greater' than p, 0 if both are
        // equal
        @Override
        public int compareTo(Point p) {
                // subtracting p.y from this.y. this will assign cmp a negative value if
                // this object has smaller y value than p, positive if it has bigger y
                // value than p, else 0
                int cmp = this.y - p.y;
                // if it is 0, using the same technique to compare x values
                if (cmp == 0) {
                        cmp = this.x - p.x;
                }
                // returning the comparison result
                return cmp;
        }
}



//PointMainMin.java


import java.util.Arrays;

public class PointMainMin {
        public static void main(String[] args) {
                // create two Point objects
                Point p1 = new Point(7, 2);
                Point p2 = new Point(4, 3);
                // print each point and its distance from the origin
                System.out.println("p1 is " + p1);
                System.out.printf("distance from origin = %3.2f\n",
                                p1.distanceFromOrigin());
                System.out.println("p2 is " + p2);
                System.out.printf("distance from origin = %3.2f\n",
                                p2.distanceFromOrigin());

                // creating an array of Point objects
                Point points[] = { new Point(2, 5), new Point(2, 6), new Point(8, 2),
                                new Point(1, 2), new Point(3, 0), new Point(7, 1),
                                new Point(9, 4) };
                // looping and printing all points before sorting
                System.out.println("Points array before sorting: ");
                for (Point p : points) {
                        System.out.println(p);
                }
                // sorting the points array. this uses the compareTo method we defined
                // in Point class to arrange Points in ascending order of y values (tie
                // breaker uses comparison of x values)
                Arrays.sort(points);
                // looping and printing all points after sorting
                System.out.println("\nPoints array after sorting: ");
                for (Point p : points) {
                        System.out.println(p);
                }
        }
}

/*OUTPUT*/

p1 is (7, 2)
distance from origin = 7.28
p2 is (4, 3)
distance from origin = 5.00
Points array before sorting: 
(2, 5)
(2, 6)
(8, 2)
(1, 2)
(3, 0)
(7, 1)
(9, 4)

Points array after sorting: 
(3, 0)
(7, 1)
(1, 2)
(8, 2)
(9, 4)
(2, 5)
(2, 6)

Related Solutions

For these exercises you are required to edit in the Comparable interface implementation, a compareTo() method,...
For these exercises you are required to edit in the Comparable interface implementation, a compareTo() method, starting with the class definition you obtained from the link, and submit that with a client that uses this ordering. If you are so inclined, you may submit a single client to drive your ordering enhancements for both classes, rather than one for each class. The exercises, for those without the text: 19. Modify the Point class from Chapter 8 so that it defines...
data structure class: a. syntax for generics b. comparable interface c.how do you implement interface answer...
data structure class: a. syntax for generics b. comparable interface c.how do you implement interface answer for all of them please. answer for all of them please
This activity will require you to apply your knowledge of interfaces – including the Comparable interface...
This activity will require you to apply your knowledge of interfaces – including the Comparable interface – in order to leverage the capabilities of the ArrayList data structure. --------- You may work individually or with a partner, but be sure that each student submits their own assignment in Canvas (and leave a comment with your partner's name if you worked with one). --------- Description: Interfaces are used to make a Class implement a behavior or set of behaviors. Recall the...
3.2. Unfortunately, you cannot modify the Rectangle class so that it implements the Comparable interface. The...
3.2. Unfortunately, you cannot modify the Rectangle class so that it implements the Comparable interface. The Rectangle class is part of the standard library, and you cannot modify library classes. Fortunately, there is a second sort method that you can use to sort a list of objects of any class, even if the class doesn't implement the Comparable interface. Comparator<T> comp = . . .; // for example, Comparator<Rectangle> comp = new RectangleComparator(); Collections.sort(list, comp); Comparator is an interface. Therefore,...
In this class add Comparable interface. In the driver program create a few objects and In...
In this class add Comparable interface. In the driver program create a few objects and In the driver program create a few objects and compare them . then create a list of those objects and sort them .A Quadratic is bigger than another Quadratic if it opens faster package pack2; /** * This is a program for defining a quadratic equation * @author sonik */ public class Quadratic { public int coeffX2 = 0; public int coeffX = 0; public...
In Java: Job class The Job implements the Comparable interface A Job object is instantiated with...
In Java: Job class The Job implements the Comparable interface A Job object is instantiated with three int variables, indicating the arrivalTime, the timeForTheJob, and the priority. When the Job is created it is given the next sequential ID starting from 1. (You should use a static variable to keep track of where you are in ID assignment.) There are also int variables for startTime, waitTime (in queue) and endTime for the Job. The following methods are required: getID, set...
In Java: Job class The Job implements the Comparable interface A Job object is instantiated with...
In Java: Job class The Job implements the Comparable interface A Job object is instantiated with three int variables, indicating the arrivalTime, the timeForTheJob, and the priority. When the Job is created it is given the next sequential ID starting from 1. (You should use a static variable to keep track of where you are in ID assignment.) There are also int variables for startTime, waitTime (in queue) and endTime for the Job. The following methods are required: getID, set...
1(a). You are required to interface and write sample programme to test the operation of the...
1(a). You are required to interface and write sample programme to test the operation of the following devices of the microcontroller board, namely (i) Push Buttons (ii) LEDs (iii) Analog input (using the potentiometer) (b). A LED is to be interfaced to pin 3 of the microcontroller board. Please draw the necessary hardware circuit to show the connection. Write a sample software to glow the LED with ON time 1 sec and OFF time 1 sec. (microcontroller is Arduino)
Find a method of ArrayList that is not in the List interface, specifically a method that...
Find a method of ArrayList that is not in the List interface, specifically a method that trims the internal array down to fit exactly. A Google search for this did work, but the JDK API of course is the definitive source. Give the method header for the method. Add a call to this method to TestArrayList.java (which is available online in TestArrayList.zip), and see that it compiles and runs fine. Now change the line creating the ArrayList to use type...
In javascript, Write a compareTo method for the Playlist class. Playlists with fewer songs on them...
In javascript, Write a compareTo method for the Playlist class. Playlists with fewer songs on them come first. Playlists with the same number of songs come in alphabetical order by playlist name. Playlists with the same number of songs and same name can be considered equivalent (though this obviously isn’t exactly true).
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT