...

View Full Version : Comparing values of two objects



souaden12
02-08-2012, 11:37 PM
Hi
I'm new to Java and just started studying it in university right now
There is an excersie where we have to create a cylinder class, calculate its volume and surface area etc

Part of the excersie is to compare the volumes of two cylinder objects in the class and return the one with the bigger volume

The following is my code so far without the comparision method
public class Cylinder
{

private double radius;
private double height;

public Cylinder()
{
radius = 0.0;
height = 0.0;
}

public Cylinder (double radius, double height)
{
this.radius = radius;
this.height = height;
}

public double getRadius()
{
return radius;
}

public double getHeight()
{
return height;
}

public void printValues()
{
System.out.println("Radius: " + radius + " Height: " + height);
}

public double volume()
{
double volume = Math.PI*Math.pow(radius,2)*height;
return volume;

}

public double surfaceArea()
{
double surfaceArea = (2*Math.PI*Math.pow(radius,2))+(2*Math.PI*radius*height);
return surfaceArea;
}

}

can anyone explain to me how I can compare the volume values of two cylinders?
I don't want solution just explanations and hints

Thanx

Fou-Lu
02-09-2012, 07:28 PM
I'd write a static method in this. Comparable and Comparator don't return objects, but you certainly could chain them so that they would be usable in a collection to sort for example.


public static Cylinder getLargerCylinder(Cylinder c1, Cylinder c2)
{
return c1.volume() >= c2.volume() ? c1 : c2;
}

Simple as that. You can chain it to comparator.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum