Write a java program which receives 3 integers as input data. These integers wil
ID: 3667601 • Letter: W
Question
Write a java program which receives 3 integers as input data. These integers will be as the length of 3 sides of a triangle. You program needs to check if the input data can make a triangle, and then prints out the result. If they cannot make a triangle, print out a message, otherwise print out the area of the triangle.
The output looks like the following:
Hints:
Show your program works on NetBeans.
run Enter first side length: 3 second side length Enter Enter third side length 5 The area of this triangle is: 6 BUILD SUCCESSFUL (total time: 10 seconds) run Enter first side length 1 Enter second side length 1 Enter third side length: 3 These sides cannot make a triangle! BUILD SUCCESSFUL (total time: 9 seconds) run: Enter first side length: 1 Enter second side length. 5 Enter third sido longth: 9 The area of this Lriangle is: 0 BUILD SUCCESSFUL (total time: 11 seconds)Explanation / Answer
import java.util.Scanner;
/**
* @author Srinivas Palli
*
*/
public class TriangleArea {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the first side length : ");
int a = input.nextInt();
System.out.print("Enter the second side length : ");
int b = input.nextInt();
System.out.print("Enter the third side length : ");
int c = input.nextInt();
if (isTriangleValid(a, b, c)) {
System.out.println("The are of this triangle is: "
+ getArea(a, b, c));
} else {
System.out.println("These sides cannot make a triangle");
}
}
/**
* Checks whether the 3 sides can form a triangle The sum of any two sides
* must be greater than the other side
*
* @param a
* @param b
* @param c
* @return
*/
public static boolean isTriangleValid(int a, int b, int c) {
if ((a + b) >= c && (a + c) >= b && (b + c) >= a) {
return true;
} else {
return false;
}
}
/**
* method to calculate area
*
* @param a
* @param b
* @param c
* @return
*/
public static int getArea(int a, int b, int c) {
int s = (a + b + c) / 2;
int x = ((s) * (s - a) * (s - b) * (s - c));
int area = (int) Math.sqrt(x);
return area;
}
}
OUTPUT:
Enter the first side length : 3
Enter the second side length : 4
Enter the third side length : 5
The are of this triangle is: 6
Enter the first side length : 1
Enter the second side length : 1
Enter the third side length : 3
These sides cannot make a triangle
Enter the first side length : 4
Enter the second side length : 5
Enter the third side length : 9
The are of this triangle is: 0
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.