Sjx類
1 package sjx; 2 /** 3 * 判斷三個數是否能組成三角形以及組成的三角形類型 4 * 2019-07-10 5 * @author L 6 * 7 */ 8 public class Sjx { 9 10 int a; 11 int b; 12 int c; 13 boolean boo = false; 14 15 public Sjx() { 16 } 17 18 public Sjx(int a, int b, int c) { 19 if (a >= b && a >= c) { 20 boo = a < (b + c) ? true : false; 21 } else if (b >= a && b >= c) { 22 boo = b < (a + c) ? true : false; 23 } else if (c >= a && c >= b) { 24 boo = c < (a + b) ? true : false; 25 } 26 } 27 28 public void showInfo(int a, int b, int c) { 29 int sjx = 0;//判斷三角形 30 if (a >= b && a >= c) { 31 // 如果任意一條邊的平方等於其他兩邊的平方之和 為直角三角形 32 // 大於 為 鈍角三角形 33 // 否則 為銳角三角形 34 if ((a * a) == (b * b + c * c)) { 35 sjx = 1; 36 } else if ((a * a) > (b * b + c * c)) { 37 sjx = 2; 38 } else { 39 sjx = 3; 40 } 41 } else if (b >= a && b >= c) { 42 if ((b * b) == (a * a + c * c)) { 43 sjx = 1; 44 } else if ((b * b) > (a * a + c * c)) { 45 sjx = 2; 46 } else { 47 sjx = 3; 48 } 49 } else if (c >= a && c >= b) { 50 if ((c * c) == (b * b + a * a)) { 51 sjx = 1; 52 } else if ((c * c) > (b * b + a * a)) { 53 sjx = 2; 54 } else { 55 sjx = 3; 56 } 57 } 58 switch (sjx) { 59 case 1: 60 System.out.println("這是一個直角三角形!"); 61 break; 62 case 2: 63 System.out.println("這是一個鈍角三角形!"); 64 break; 65 case 3: 66 System.out.println("這是個銳角三角形!"); 67 } 68 } 69 }
測試類
1 package sjx; 2 3 import java.util.Scanner; 4 5 public class Main { 6 static Scanner sc=new Scanner(System.in); 7 public static void main(String[] args) { 8 String xz = ""; 9 do { 10 // 輸入三條邊長 11 System.out.println("請輸入第1條邊長:"); 12 int a = sc.nextInt(); 13 System.out.println("請輸入第2條邊長:"); 14 int b = sc.nextInt(); 15 System.out.println("請輸入第3條邊長:"); 16 int c = sc.nextInt(); 17 // 判斷是否構成三角形 滿足條件:任意兩邊之和大於第三邊 18 Sjx shape = new Sjx(a, b, c); 19 if (shape.boo) { 20 shape.showInfo(a, b, c); 21 } else { 22 System.out.println("這不能構成三角形!"); 23 } 24 System.out.println("是否繼續(輸入y繼續否則退出):"); 25 xz = sc.next(); 26 27 } while ("y".equals(xz)); 28 System.out.println("程序結束!"); 29 } 30 }