Question

A class named Part has two fields: category (int) and cost (double). Write a single Comparable...

A class named Part has two fields:

category (int) and cost (double). Write a single

Comparable compareTo method that orders Part objects by ascending categories and by

ascending cost within each category

For example:

. . . .

2 12.96

2 45.12

2 87.00

2 100.38

2 253.93

. . . .

10 34.12

10 34.98

10 294.23

10 3467.89

. . . .

0 0
Add a comment Improve this question Transcribed image text
Answer #1

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. Thanks

// required compareTo() method which should be a included inside Part class.

// this method returns a negative value if this Part object should occur

// before other, 0 if both have equal ordering, positive value if other

// should come before this.

public int compareTo(Part other) {

      // comparing category of this Part object and other

      int cmp = this.category - other.category;

      // if cmp is 0, it means that both objects have same category, in which

      // case we have to compare costs, but if cmp is not 0 (either negative

      // or positive), simply returning it

      if (cmp != 0) {

            return cmp;

      }

      // if cmp is 0, comparing costs

      if (this.cost < other.cost) {

            // this object has low cost than other

            return -1;

      } else if (this.cost > other.cost) {

            // this object has more cost than other

            return 1;

      }

      // same category, same cost

      return 0;

}

Add a comment
Know the answer?
Add Answer to:
A class named Part has two fields: category (int) and cost (double). Write a single Comparable...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT