你的位置:首页 > Java教程

[Java教程]Java 类和对象7


创建一个三角形类,成员变量三边,方法求周长,创建类主类A来测试它。

 1 public class sanjiaoxing { 2  3   private double a; 4   private double b; 5   private double c; 6   double zhouchang; 7  8   public double getA() { 9     return a;10   }11 12   public void setA(double a) {13     this.a = a;14   }15 16   public double getB() {17     return b;18   }19 20   public void setB(double b) {21     this.b = b;22   }23 24   public double getC() {25     return c;26   }27 28   public void setC(double c) {29     this.c = c;30   }31 32   sanjiaoxing(double a, double b, double c) {33     this.a = a;34     this.b = b;35     this.c = c;36   }37 38   public void getZhouChang() {39     zhouchang = 0;40     if ((a + b > c && a + c > b && b + c > a) && (a >= 0 && b >= 0 && c >= 0)) {41       zhouchang = a + b + c;42     } else {43       System.out.println(this.a + "\t" + this.b + "\t" + this.c + "三个数不能构成三角形。");44     }45     if (zhouchang != 0) {46       System.out.println(this.a + "\t" + this.b + "\t" + this.c + "三个数成功构成三角形 ,周长=" + zhouchang);47     }48   }49 50   public static void main(String[] args) {51     sanjiaoxing s1 = new sanjiaoxing(1.4, 2.5, 3);52     s1.getZhouChang();53 54     sanjiaoxing s2 = new sanjiaoxing(1, 3, 4);55     s2.getZhouChang();56 57     sanjiaoxing s3 = new sanjiaoxing(1, 5, 5);58     s3.getZhouChang();59 60     sanjiaoxing s4 = new sanjiaoxing(3, -4, 5);61     s4.getZhouChang();62   }

运行: