Free Response Practice Question (with solution)- Triangle Project


<-- Back to AP CSA Exam Solutions Next to Dice Game Project -->





Triangle Project


Part 1:Triangle.java

Write the complete class definition for the Triangle class. The Triangle class consists of the following:


Additionally,


Part 2: TriangleRunner.java

Write the complete class definition for the runner class named TriangleRunner class, that makes use of the Triangle class. The main method of the TriangleRunner class should do the following:


Solution:


Part 1:Triangle.java


Default Constructor

    public Triangle()
    {
        side1= 0.0;
        side2= 0.0;
        side3= 0.0;
    }


Three Overloaded Constructors

    public Triangle(double side)
    {
        side1= side;
        side2= side;
        side3= side;
    }
    
    public Triangle(double side1, double side2)
    {
        this.side1= side1;
        this.side2= side1;
        this.side3= side2;
    }
    
    public Triangle(double side1, double side2, double side3)
    {
        this.side1= side1;
        this.side2= side2;
        this.side3= side3;
    }


Helper Method

    public String getTriangleType()
    {
        if ((this.side1 == this.side2) && (this.side1 == this.side3))
        {
            if (side1==0)
                return "generic";
                else
                    return "equilateral";
        }
        else if ((this.side1 == this.side2) || (this.side2 == this.side3) || (this.side2 == this.side3))
        {
            return "isosceles";
        }
        else return "scalene";
    }

Part 2:TriangleRunner.java


Using Constructors

        Triangle genTri = new Triangle();
        Triangle equiTri = new Triangle(2.1);
        Triangle isoTri = new Triangle(2.1, 3.5);
        Triangle ScaTri = new Triangle(2.1, 3.5, 4.3);


Using Helper Method

        System.out.println("Triangle type for genTri object is: "+ genTri.getTriangleType());
        System.out.println("Triangle type for equiTri object is: "+ equiTri.getTriangleType());
        System.out.println("Triangle type for isoTri object is: "+ isoTri.getTriangleType());
        System.out.println("Triangle type for ScaTri object is: "+ ScaTri.getTriangleType());



Java project files (with Runner code):


<-- Back to AP CSA Exam Solutions Next to Dice Game Project -->