Java: Check if three given side lengths can make a triangle or not
Java Basic: Exercise-195 with Solution
Check Triangle Validity
Write a Java program to check if three given side lengths (integers) can make a triangle or not.
Visual Presentation:
Sample Solution:
Java Code:
// Import Scanner class from java.util package for user input
import java.util.*;
// Main class for the solution
public class Solution {
// Main method to execute the solution
public static void main(String[] args) {
// Create a Scanner object for user input
Scanner in = new Scanner(System.in);
// Prompt the user to input the first side of the triangle
System.out.print("Input side1: ");
// Read the user input as an integer
int s1 = in.nextInt();
// Prompt the user to input the second side of the triangle
System.out.print("Input side2: ");
// Read the user input as an integer
int s2 = in.nextInt();
// Prompt the user to input the third side of the triangle
System.out.print("Input side3: ");
// Read the user input as an integer
int s3 = in.nextInt();
// Display the result of the isValidTriangle function
System.out.print("Is the said sides form a triangle: " + isValidTriangle(s1, s2, s3));
}
// Function to check if the given sides form a valid triangle
public static boolean isValidTriangle(int a, int b, int c) {
// Check the triangle inequality theorem to determine validity
return (a + b > c && b + c > a && c + a > b);
}
}
Sample Output:
Input side1: 5 Input side2: 6 Input side3: 8 Is the said sides form a triangle: true
Flowchart:
Java Code Editor:
Company: LinkedIn
Contribute your code and comments through Disqus.
Previous: Write a Java program to find the all positions of a given number in a given matrix. If the number not found print ("Number not found!").
Next: Write a Java program to create a spiral array of n * n sizes from a given integer n.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/java-exercises/basic/java-basic-exercise-195.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics