Im trying to make a code to calculate perimeter however the result is 0.0 units
My support class
/*
*Calculates Perimeter of three triangles
*/
public class Triangle{
//data field declarations
public int x1; // coordinates of first point of the triangle
public int y1;
public int x2; // coordinates of second point of the triangle
public int y2;
public int x3; // coordinates of third point of the triangle
public int y3;
private double side1, side2, side3, perimeter;
private String m;
public Triangle(String m, int x1, int y1, int x2, int y2, int x3, int y3)
{
this.m = m;
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.x3 = x3;
this.y3 = y3;
}
public void calculateSideLength()
{
side1 = Math.sqrt(Math.pow((x2-x1),2)*Math.pow((y2-y1),2));
side2 = Math.sqrt(Math.pow((x3-x2),2)*Math.pow((y3-y2),2));
side3 = Math.sqrt(Math.pow((x3-x1),2)*Math.pow((y3-y1),2));
}
public void calculateTrianglePerimeter()
{
perimeter = side1+side2+side3;
}
public String toString()
{
return "Triangle " + m + " perimeter is " + perimeter + " units";
}
}
My application class
/*
*Calculates Perimeter of three triangles
*/
public class TriangleApp{
public static void main (String[] args){
Triangl开发者_运维百科e a = new Triangle("A", 0,3,3,4,1,9);
System.out.println(a.toString());
}
}
I get Triangle A perimeter is 0.0 units Could someone tell me what im i doing wrong?
You're not calling calculateSideLength()
, or calculateTrianglePerimeter()
. Call those (from the constructor, in that order, or from the user code) and the values will be set.
You are not calling the function calculateTrianglePerimeter()
after creating the Triangle Object, though the implementation is there. What you can do is, towards the end of the constructor, call the necessary functions, in proper order, to calculate the attributes such as side length and perimeter.
精彩评论