1. 程式人生 > >封裝-判斷三角形案例

封裝-判斷三角形案例

ner 負數 sca test new lse () angle nbsp

 1 //三角形類
 2 public class Triangle {
 3     private int a;  //三角形第一條邊
 4     private int b;  //三角形第二條邊
 5     private int c;  //三角形第三條邊
 6     
 7     public int getA() {
 8         return a;
 9     }
10     public void setA(int a) {
11         if(a<=0) {
12             System.out.println("三角形的邊不能為0或負數");        
13 } 14 this.a = a; 15 } 16 public int getB() { 17 return b; 18 } 19 public void setB(int b) { 20 if(b<=0) { 21 System.out.println("三角形的邊不能為0或負數"); 22 } 23 this.b = b; 24 } 25 public int getC() { 26 return c;
27 } 28 public void setC(int c) { 29 if(c<=0) { 30 System.out.println("三角形的邊不能為0或負數"); 31 } 32 this.c = c; 33 } 34 35 public void isTriangle() { 36 //判斷是否能構成三角形,如果是三角形,判斷是哪種三角形,如果不是則提示 37 if(this.a+this.b>this.c && this
.a+this.c>this.b && this.b+this.c>this.a) { 38 shape(); 39 }else { 40 System.out.println("這不能構成三角形"); 41 } 42 } 43 44 public void shape() { 45 String shape=""; 46 //判斷構成哪種三角形 47 if(a*a==b*b+c*c || b*b==a*a+c*c || c*c==a*a+b*b) { 48 shape="這是一個直角三角形"; 49 }else if(a*a>b*b+c*c || b*b>a*a+c*c || c*c>a*a+b*b) { 50 shape="這是一個鈍角三角形"; 51 }else { 52 shape="這是一個銳角三角形"; 53 } 54 System.out.println(shape); 55 } 56 57 }
 1 import java.util.Scanner;
 2 
 3 //測試三角形類
 4 public class TriangleTest {
 5 
 6     public static void main(String[] args) {
 7         Scanner input = new Scanner(System.in);
 8         String answer="";
 9         do {
10             Triangle t=new Triangle();
11             System.out.print("請輸入第一條邊:");        
12             t.setA(input.nextInt());
13             System.out.print("請輸入第二條邊:");
14             t.setB(input.nextInt());
15             System.out.print("請輸入第三條邊:");
16             t.setC(input.nextInt());
17             t.isTriangle();
18             System.out.print("繼續嗎?(y/n)");
19             answer=input.next();
20             
21         }while(answer.equalsIgnoreCase("y"));
22         System.out.println("謝謝使用!");
23         
24     }
25 
26 }

封裝-判斷三角形案例