Create a class named MyTriangle that contains the following three methods: The i
ID: 3554619 • Letter: C
Question
Create a class named MyTriangle that contains the following three methods:
The isValid method returns true if the sum of the two shorter sides is greater than the longest side.
Given the lengths of the three sides of the triangle, the area of the triangle can be computed using Heron's formula.
The type method returns one of the following strings: "Equilateral", "Isosceles", "Scalene", "Invalid Triangle". You can determine the type if a, b, and c represent the sides in ascending order, you must first determine if it isValid. If it is valid, the triangle is equilateral if a == c. Isosceles if a == b or b == c. Scalene otherwise.
Write a test program that reads three sides for a triangle, and displays the type. If the triangle is valid, compute and output the area.
Explanation / Answer
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class MyTriangle {
public MyTriangle() {
}
public static boolean isValid(double sidea, double sideb, double sidec) {
if(sidea<sideb){
if(sideb<sidec){
return (sidea+sideb)>sidec;
} else {
return (sidea+sidec)>sideb;
}
} else if(sideb==sidea){
if(sidea<sidec){
return (sidea+sideb)>sidec;
} else{
return (sidea+sidec)>sideb;
}
} else {
if(sidea<sidec){
return (sidea+sideb)>sidec;
} else {
return (sideb+sidec)>sidea;
}
}
}
public static double area(double sidea, double sideb, double sidec){
double s = (sidea+sideb+sidec)/2;
return Math.sqrt(s*(s-sidea)*(s-sideb)* (s-sidec));
}
public static String type(double a, double b, double c) {
if(isValid(a, b, c)) {
if(a==b || b==c){
if(a==c) {
return "Equilateral";
} else {
return "Isosceles";
}
} else {
return "Scalene";
}
}
return "Not a triangle!";
}
public static void main(String[] args) {
while(true){
System.out.println("Enter three numbers (ex. 3 4 5)");
// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
MyTriangle tri = new MyTriangle();
try {
String[] input = br.readLine().split(" ");
double a = Double.valueOf(input[0]);
double b = Double.valueOf(input[1]);
double c = Double.valueOf(input[2]);
System.out.println("a=" + a + " b=" + b + " c=" + c + "Is valid = " + tri.isValid(a, b, c));
System.out.println("Area = " + tri.area(a, b, c));
System.out.println("Is valid = " + tri.type(a, b, c));
} catch(Exception e) {
System.out.println(e.toString());
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.