-
-
Save Nguyensane/c1c7b4e8a84e5bb481d3 to your computer and use it in GitHub Desktop.
Array of Objects Area Function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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