SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Conditional Execution
Exercise:
Exercises
Question:9 | ISBN:9780136091813 | Edition: 2

Question

Write the method called printTriangleType referred to in Self-Check Problem 22. This method accepts three integer arguments representing the lengths of the sides of a triangle and prints the type of triangle that these sides form. Here are some sample calls to printTriangleType:
printTriangleType(5, 7, 7);
printTriangleType(6, 6, 6);
printTriangleType(5, 7, 8);
printTriangleType(2, 18, 2);

The output produced by these calls should be
isosceles
equilateral
scalene
isosceles
Your method should throw an IllegalArgumentException if passed invalid values, such as ones where one side’s length is longer than the sum of the other two, which is impossible in a triangle. For example, the call of printTriangleType(2, 18, 2); should throw an exception.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Program:

public class Ch04Ex09
{
	public static void main(String[] args)
	{
		printTriangleType(5, 7, 7);
		printTriangleType(6, 6, 6);
		printTriangleType(5, 7, 8);
		printTriangleType(2, 18, 2);
	}

	public static void printTriangleType(int side1, int side2, int side3)
	{
		if(side1 > side2 + side3 || side2 > side3 + side1 || side3 > side1 + side2)
		{
			throw new IllegalArgumentException("Invalid sides in a triangle!");
		}
		
		if (side1 == side2 && side2 == side3)
		{
			System.out.println("equilateral");
		}
		else if (side1 == side2 || side2 == side3 || side1 == side3)
		{
			System.out.println("isosceles");
		}
		else
		{
			System.out.println("scalene");
		}
	}
}

Output:

isosceles
equilateral
scalene
Exception in thread "main" java.lang.IllegalArgumentException: Invalid sides in a triangle!
	at Ch04Ex09.printTriangleType(Ch04Ex09.java:15)
	at Ch04Ex09.main(Ch04Ex09.java:8)

 

0 0

Discussions

Post the discussion to improve the above solution.