**3.19(计算三角形的周长)编写程序,读取三角形的三条边,如果输入值合法就计算这个三角形的周长;否则,显示这些输入值不合法。如果任意两条边的和大于第三边,那么输入值都是合法的。 **3.19(Compute the perimeter of a triangle)(Compute the perimeter of a triangle) Write a program that reads three edges for a triangle and computes the perimeter if the input is valid. Otherwise, display that the input is invalid. The input is valid if the sum of every pair of two edges is greater than the remaining edge.
参考代码:
方法一:package chapter03; import java.util.Scanner; public class Code_19another { public static void main(String[] args) { double edge1,edge2,edge3,perimeterTriangle = 0; // Prompt the user to enter three edges System.out.print("Enter the first edge of the triangle: "); Scanner input = new Scanner(System.in); edge1 = input.nextDouble(); System.out.print("Enter the second edge of the triangle: "); edge2 = input.nextDouble(); System.out.print("Enter the third edge of the triangle: "); edge3 = input.nextDouble(); // Check whether it's a triangle or it's not if(edge1+edge2>edge3 && edge1+edge3>edge2 && edge2+edge3>edge1) perimeterTriangle = edge1 + edge2 + edge3; else System.out.println("The input is invalid"); if(perimeterTriangle != 0) System.out.println("The perimeter of the triangle is " + perimeterTriangle); input.close(); } } 方法二:package chapter03; import java.util.Arrays; import java.util.Scanner; public class Code_19 { public static void main(String[] args){ Scanner input = new Scanner(System.in); System.out.print("Enter three integers: "); int a = input.nextInt(); int b = input.nextInt(); int c = input.nextInt(); int[] arr = {a,b,c}; Arrays.sort(arr); if (arr[0] + arr[1] > arr[2]) System.out.println("legitimate"); else System.out.println("not legitimate"); } }结果显示:
Enter the first edge of the triangle: 3 Enter the second edge of the triangle: 4 Enter the third edge of the triangle: 5 The perimeter of the triangle is 12.0 Process finished with exit code 0