In: Computer Science
Write a program named Triangle.java that asks for the lengths of the three sides of a triangle and computes the perimeter if the input is valid. The input is valid if the sum of every pair of two sides is greater than the remaining side. For example, the lengths 3, 4, and 5 define a valid triangle: 3 plus 4 is greater than 5; 4 plus 5 is greater than 3, and 5 plus 3 is greater than 4. However, the lengths 7, 2, and 4 do not specify a valid triangle because 2 plus 4 is not greater than 7.
Here is the output from running the program twice. Your program’s output does not have to look exactly like this, but it must convey the same information. Use input is shown in bold.
Enter lengths of sides of the triangle: 3 4 5 The perimeter of the triangle is 12.0 Enter lengths of sides of the triangle: 7 2 4 Those sides do not specify a valid triangle.
// Screenshot of the code & output
// Code to copy
Triangle.java
import java.util.Scanner;
public class Triangle {
public static void main(String[] args) {
double side1,side2,side3;
Scanner input = new
Scanner(System.in);
System.out.print("Enter lengths of sides of the triangle: ");
side1 = input.nextDouble();
side2 = input.nextDouble();
side3 = input.nextDouble();
// function calling and print output
if ((checkValidity(side1, side2, side3))==1) {
double perimeter = side1 + side2 + side3;
System.out.println("The perimeter of the triangle is " +
perimeter
+ ".");
} else {
System.out.println("Those sides do not specify a valid
triangle.");
}
input.close();
}
// Function to calculate for validity
private static int checkValidity(double a, double b,
double c) {
// check condition
if (a + b <= c || a + c <= b || b + c <= a)
return 0;
else
return 1;
}
}