Defining and Testing a Simple Method with JAVA: Write a method called triangleTy
ID: 666589 • Letter: D
Question
Defining and Testing a Simple Method with JAVA:
Write a method called triangleType. The triangleType method is sent 3 integers A, B, and C which are assumed to represent the sides of a triangle. The sides can be sent in any order, but the method must put the sides in ascending order in order to determine the type of triangle. The method returns a string indicating if the triangle is EQUILATERAL, ISOSCELES, SCALENE, or INVALID TRIANGLE.
If A, B, and C, represent the sides in ascending order, the rules for determining the triangle type are as follows: if A + B <= C, then the sides do not represent a valid triangle. if A = C (all the sides must be the same length) then the triangle is EQUILATERAL. if A = B or B = C, then the triangle is ISOSCELES; otherwise the triangle is SCALENE.
After you have defined the method, you must:
Write a main method to do the following: Repeatedly have the user enter 3 integers. Call the triangleType method and display the return type. Be sure you don’t have an infinite loop (allow the user to quit).
Explanation / Answer
import java.util.Scanner;
public class TriangleTester {
public static void main(String[] args) {
Scanner keybd = new Scanner(System.in);
int A, B, C;
System.out.println("Triangle Tester");
do {
System.out.println("Enter 3 sides (negative number to quit)");
System.out.print("Enter side A: ");
A = keybd.nextInt();
if (A<0) break;
System.out.print("Enter side B: ");
B = keybd.nextInt();
if (B<0) break;
System.out.print("Enter side C: ");
C = keybd.nextInt();
if (C<0) break;
System.out.println(triangleType (A, B, C));
} while (true);
} // end main()
public static String triangleType (int A, int B, int C) {
if (A + B <= C) return "INVALID TRIANGLE";
if (A==B && A==C) return "EQUILATERAL";
if (A==B || A==C || B==C) return "ISOSCELES";
return "SCALENE";
} // end triangleType()
} // end class TriangleTester
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.