In: Computer Science
uppose you have a pre-existing class Dieter that models a person trying to monitor diet and weight to improve his/her Body Mass Index (BMI) rating. The class has the following data and behavior:
Field/Constructor/Method |
Description |
private String name |
the dieter's full name, such as "John Smith" |
private int height |
the dieter's height, in inches |
private int weight |
the dieter's weight, in pounds |
public Dieter(String name, int h, int w) |
makes a dieter with given name, height, weight |
public String getName() |
returns the dieter's name |
public int getHeight() |
returns the dieter's height |
public int getWeight() |
returns the dieter's weight |
public double getBMI() |
computes the dieter's Body Mass Index (BMI), which is (weight / height2) · 703 |
public void gain(int pounds) |
called when the dieter gains weight |
public void lose(int pounds) |
called when the dieter loses weight |
Make Dieter objects comparable to each other using the Comparable interface.
You are just writing a compreTo method for the class and not any other method.
Write the compareTo method for the class Dieter using the following criteria.
// Dieter.java
public class Dieter implements Comparable<Dieter> {
private String name; // the dieter's full name,
such as "John Smith"
private int height; // the dieter's height, in
inches
private int weight; // the dieter's weight, in
pounds
// constructor that creates a dieter with given name,
height, weight
public Dieter(String n, int h, int w)
{
name = n;
height = h;
weight = w;
}
// returns the dieter's name
public String getName()
{
return name;
}
// returns the dieter's height
public int getHeight()
{
return weight;
}
// returns the dieter's weight
public int getWeight()
{
return weight;
}
// computes the dieter's Body Mass Index (BMI), which
is (weight / height2) • 703
public double getBMI()
{
return
(((double)weight)/Math.pow(height,2))*703;
}
// method called when the dieter gains weight
public void gain(int pounds)
{
weight += pounds;
}
// method called when the dieter loses weight
public void lose(int pounds)
{
weight -= pounds;
if(weight < 0)
weight =
0;
}
/*
* method to compare 2 Dieter and returns
* < 0, if this Dieter < other
* > 0, if this Dieter > other
* = 0, if this Dieter = other
*/
@Override
public int compareTo(Dieter other) {
// compare Dieter based on
BMI
if(getBMI() <
other.getBMI())
return -1;
else if(getBMI() >
other.getBMI())
return 1;
else
{
// BMI are
equal
// compare
Dieter based on height
// shorter
person is considered to be "less than" the taller one
if(height <
other.height)
return -1;
else if(height
> other.height)
return 1;
else // same
height, compare the Dieters based on name
// The dieter whose name comes first in
alphabetical order is considered
// "less than" the one whose name comes later in
ABC order.
return name.compareTo(other.name);
}
}
}
//end of Dieter.java