Skip to content

Instantly share code, notes, and snippets.

@Nguyensane
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nguyensane/c1c7b4e8a84e5bb481d3 to your computer and use it in GitHub Desktop.
Save Nguyensane/c1c7b4e8a84e5bb481d3 to your computer and use it in GitHub Desktop.
Array of Objects Area Function
package labNotGraded;
public class Triangle {
public static void main(String[] args) {
Triangle[] triangleArray = new Triangle[4];
for (int i = 0; i < triangleArray.length; i++) {
triangleArray[i] = new Triangle(i+1, i+1);
System.out.printf("Triangle %d: Base = %f \t Height = %f \t Area = %f \n", i+1, triangleArray[i].base, triangleArray[i].height, triangleArray[i].getArea());
}
System.out.printf("Sum of areas: %f", sumArrayOfTriangles(triangleArray));
}
private double base;
private double height;
Triangle(){
}
Triangle(double p_base, double p_height){
this.base = p_base;
this.height = p_height;
}
public void display(Triangle tri1)
{
System.out.printf("Base: %.2f ", tri1.base);
System.out.printf("Height: %.2f ", tri1.height);
}
public double getArea()
{
return (base * height) / 2;
}
public static double sumArrayOfTriangles(Triangle[] triangleArray){
double sum = 0;
for (int i = 0; i < triangleArray.length; i++)
{
sum += triangleArray[i].getArea();
}
return sum;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment