Question

Java Please - Design and implement a class Triangle. A constructor should accept the lengths of...

Java Please - Design and implement a class Triangle. A constructor should accept the lengths of a triangle’s 3 sides (as integers) and verify that the sum of any 2 sides is greater than the 3rd(i.e., that the 3 sides satisfy the triangle inequality). The constructor should mark the triangle as valid or invalid; do not throw an exception. Provide get and set methods for the 3 sides, and recheck for validity in the set methods. Provide a toString method to display the triangle and whether it is a valid triangle. Provide 4 other boolean-returning methods: isRight, isIsosceles (only 2 sides are equal), isEquilateral, and isInvalid. Provide a driver in a separate source file to test your class.

Please make sure to use integers, not doubles.

All instance variables must be private

Must include a toString method as stated

The main routine must be in a separate from the .java file(s) for the class(es) that are being defined - otherwise they are not reusable.

Then

Modify the Triangle class to throw an exception in the constructor and set routines if the triangle is not valid (i.e., does not satisfy the triangle inequality). Modify the main routine to prompt the user for the sides of the triangle and to catch the exception and re-prompt the user for valid triangle sides. In addition, for any valid triangle supply a method to compute and display the area of the triangle using Herod’s method: where a, b, and c are the lengths of the sides and p is 1/2 of the perimeter of the triangle, A = [p(p-a)(p-b)(p-c)]^1/2. The area, A, should be a double displayed with 2 digits after the decimal point. Supply a getPerimeter method to compute the perimeter as an integer. Display the triangle, its area and perimeter. Allow the user to repeatedly enter triangle sides and do not exit the process until the user enters 0 for a side length. Here is a sample dialog:

Enter the sides of the triangle as integers

Enter 0 to quit:

Enter side 1: 3

Enter side 2: 4

Enter side 3: 5

Triangle with sides: 3 4 5

Is right

Is not isosceles

Is not equilateral

Area = 6.00

Perimeter = 12

Enter the sides of the triangle as integers

Enter 0 to quit:

Enter side 1: 1

Enter side 2: 1

Enter side 3: 2

Not a valid triangle

Enter the sides of the triangle as integers

Enter 0 to quit:

Enter side 1: -1

Enter side 2: 2

Enter side 3: 3

Not a valid triangle

Enter the sides of the triangle as integers

Enter 0 to quit:

Enter side 1: 1

Enter side 2: 2

Enter side 3: 2

Is not right

Is isosceles

Is not equilateral

Area = 0.97

Perimeter = 5

Enter the sides of the triangle as integers

Enter 0 to quit:

Enter side 1: 0

Exiting

---------------------------------------------------------------------------

Please and thank you!!

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Please find the answer below, all the details are mentioned in the comments:

Triangle.java
public class Triangle {
    //fields to store the values
    private int sideA;
    private int sideB;
    private int sideC;
    private boolean isValid;

    //constructor
    public Triangle(int sideA, int sideB, int sideC) throws Exception {
        this.sideA = sideA;
        this.sideB = sideB;
        this.sideC = sideC;

        if (checkValid()) {
            isValid = true;
        } else {
            isValid = false;
        }
    }


    // Function to calculate for validity
    public boolean checkValid() throws Exception {
        // check condition
        if (sideA + sideB <= sideC || sideA + sideC <= sideB || sideB + sideC <= sideA)
            throw  new Exception("Not a valid triangle");
        else
            return true;
    }

    //getter and setters
    public int getSideA() {
        return sideA;
    }

    public void setSideA(int sideA) throws Exception {
        this.sideA = sideA;
        if (checkValid()) {
            isValid = true;
        } else {
            isValid = false;
        }
    }

    public int getSideB() {
        return sideB;
    }

    public void setSideB(int sideB) throws Exception {
        this.sideB = sideB;
        if (checkValid()) {
            isValid = true;
        } else {
            isValid = false;
        }
    }

    public int getSideC() {
        return sideC;
    }

    public void setSideC(int sideC) throws Exception {
        this.sideC = sideC;
        if (checkValid()) {
            isValid = true;
        } else {
            isValid = false;
        }
    }

    //check of the triangle is right
    public boolean isRight() {
        if (sideA * sideA + sideB * sideB == sideC * sideC
                || sideB * sideB + sideC * sideC == sideA * sideA
                || sideA * sideA + sideC * sideC == sideB * sideB) {
            return true;
        }
        return false;
    }

    //check if the triangle is isosceles is not
    public boolean isIsosceles() {
        if (sideA == sideB || sideB == sideC || sideC == sideA) {
            return true;
        }
        return false;
    }

    //check if the triangle is equilateral or not
    public boolean isEquilateral() {
        if (sideA == sideB && sideB == sideC) {
            return true;
        }
        return false;
    }

    //check if the triangle is valid or not
    public boolean isInvalid() throws Exception {
        return checkValid();
    }

    //to print the details of the triangle
    @Override
    public String toString() {
        return "Triangle with sides:" + sideA + " " + sideB + " " + sideC;
    }

    //get the area of the triangle
    public double area() {
        int perimeter = perimeter() / 2;
        double area = (perimeter) * (perimeter - sideA) * (perimeter - sideB) * (perimeter - sideC);
        area = Math.sqrt(area);
        return area;
    }

    //get the perimeter of the triangle
    public int perimeter(){
        return sideA + sideB + sideC;
    }
}
TriangleTest.java
import java.util.Scanner;

public class TriangleTest {
    //main method to test the triangle class
    public static void main(String[] args) {
        //to check if continue or not
        boolean continueLoop = true;
        Scanner sc = new Scanner(System.in);
        int a, b, c;
        while (continueLoop) {
            //get the values from the user
            System.out.println("Enter the sides of the triangle as integers");
            System.out.println("Enter 0 to quit:");

            System.out.print("Enter side 1: ");
            a = sc.nextInt();
            if (a == 0) {
                continueLoop = false;
                break;
            }

            System.out.print("Enter side 2: ");
            b = sc.nextInt();

            System.out.print("Enter side 3: ");
            c = sc.nextInt();

            //check all the details
            try {
                Triangle triangle = new Triangle(a, b, c);
                System.out.println(triangle.toString());
                if (triangle.isRight())
                    System.out.println("Is right");
                else
                    System.out.println("Is not right");

                if (triangle.isIsosceles())
                    System.out.println("Is Isosceles");
                else
                    System.out.println("Is not isosceles");

                if (triangle.isEquilateral())
                    System.out.println("Is equilateral");
                else
                    System.out.println("Is not equilateral");

                System.out.printf("Area = %.2f\n",triangle.area());
                System.out.println("Perimeter = " + triangle.perimeter());
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }

        }
    }
}

Output:

Please let us know in the comments if you face any problems.

Add a comment
Know the answer?
Add Answer to:
Java Please - Design and implement a class Triangle. A constructor should accept the lengths of...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Modify the Triangle class (from previous code, will post under this) to throw an exception in...

    Modify the Triangle class (from previous code, will post under this) to throw an exception in the constructor and set routines if the triangle is not valid (i.e., does not satisfy the triangle inequality). Modify the main routine to prompt the user for the sides of the triangle and to catch the exception and re-prompt the user for valid triangle sides. In addition, for any valid triangle supply a method to compute and display the area of the triangle using...

  • (JAVA) Implement a Triangle class. Any triangle can be represented by its THREE sides. Therefore,...

    (JAVA) Implement a Triangle class. Any triangle can be represented by its THREE sides. Therefore, your class will have THREE private member variables → side1, side2 and side3. Use the double data type to represent the triangle sides. In addition, please provide public methods that perform the following FIVE tasks: ▪ An input method that obtains the appropriate values for the three sides from the user. While entering the values of the three sides, please remember the triangle property that...

  • (The Triangle class) Design a class named Triangle that extends the GeometricObject class. The Triangle class...

    (The Triangle class) Design a class named Triangle that extends the GeometricObject class. The Triangle class contains: - Three float data fields named side1, side2, and side3 to denote the three sides of the triangle. - A constructor that creates a triangle with the specified side1, side2, and side3 with default values 1.0. - The accessor methods for all three data fields. - A method named getArea() that returns the area of this triangle. - A method named getPerimeter() that...

  • java language Problem 3: Shape (10 points) (Software Design) Create an abstract class that represents a Shape and contains abstract method: area and perimeter. Create concrete classes: Circle, Rectang...

    java language Problem 3: Shape (10 points) (Software Design) Create an abstract class that represents a Shape and contains abstract method: area and perimeter. Create concrete classes: Circle, Rectangle, Triangle which extend the Shape class and implements the abstract methods. A circle has a radius, a rectangle has width and height, and a triangle has three sides. Software Architecture: The Shape class is the abstract super class and must be instantiated by one of its concrete subclasses: Circle, Rectangle, or...

  • Java programming 1. (Triangle class) Design a new Triangle class that extends the abstract GeometricObject class....

    Java programming 1. (Triangle class) Design a new Triangle class that extends the abstract GeometricObject class. Draw the UML diagram for the classes Triangle and GeometricObject and then implement the Triangle class. Write a test program that prompts the user to enter three sides of the triangle, a color, and a Boolean value to indicate whether the triangle is filled. The program should create a Triangle object with these sides and set the color and filled properties using the input....

  • Java Lab In this lab, you will be implementing the following class hierarchy. Your concrete classes...

    Java Lab In this lab, you will be implementing the following class hierarchy. Your concrete classes must call the superclass constructor with the proper number of sides (which is constant for each concrete shape). The perimeter method is implemented in the superclass as it does not change based on the number of sides. The area method must be overridden in each subclass as the area is dependent on the type of polygon. The areas of an equilateral triangle, square, and...

  • Introduction to Java:Design a class named Triangle that extends GeometricObject.

    Please include comments in the program .The program must be able to be compiled.Design a class named Triangle that extends GeometricObject. This class contains:* Three double data fields named side1, side2, and side3 with default values 1.0 to denote the three sides of a triangle.* A no-arg constructor that creates a default triangle.* A constructor that creates a triangle with the specified side1, side2, and side3.* The accessor methods for all three data fields.* A method named getArea() that returns...

  • You will be creating a driver class and 5 class files for this assignment. The classes...

    You will be creating a driver class and 5 class files for this assignment. The classes are Shape2D (the parent class), Circle, Triangle, and Rectangle (all children of Shape2D) and Square (child of Rectangle). Be sure to include a message to the user explaining the purpose of the program before any other printing to the screen. Within the driver class, please complete the following tasks: Instantiate a Circle object with 1 side and a radius of 4; print it Update...

  • Please write in dr java Here is the driver: import java.util.*; public class SquareDriver { public...

    Please write in dr java Here is the driver: import java.util.*; public class SquareDriver { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); String input =""; System.out.println("Welcome to the easy square program"); while(true) { System.out.println("Enter the length of the side of a square or enter QUIT to quit"); try { input = keyboard.nextLine(); if(input.equalsIgnoreCase("quit")) break; int length = Integer.parseInt(input); Square s = new Square(); s.setLength(length); s.draw(); System.out.println("The area is "+s.getArea()); System.out.println("The perimeter is "+s.getPerimeter()); } catch(DimensionException e)...

  • Welcome to the Triangles program Enter length 1: 3 Enter length 2: 5 Enter length 3:...

    Welcome to the Triangles program Enter length 1: 3 Enter length 2: 5 Enter length 3: 5 Enter the base: 5 Enter the height: 8 --------------------- The triangle is Isosceles since it has two equal length sides. Isosceles triangle also has two equal angles The area is: 20 The permimeter is: 13 Continue? (y/n): y Enter length 1: 10 Enter length 2: 10 Enter length 3: 10 Enter the base: 10 Enter the height: 7 --------------------- The triangle is Equilateral...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT