JAVA代码(面向对象程序设计)

JAVA代码

1.一元二次方程

定义方法: class EquationA { double a, b, c; double delta; EquationA(double x, double y, double z) { a = x; this.b = y; c = z; getDela(); } private void getDela() { delta = b * b - 4 * a * c; } double getRoot1() { double r1 = 0; r1 = (-b + Math.sqrt(delta)) / (2 * a); return r1; } double getRoot2() { double r1 = 0; r1 = (-b - Math.sqrt(delta)) / (2 * a); return r1; }

public String toString() { String str = a + \ return str; } }

测试类:

public class testE { public static void main(String[] args) {

}

}

EquationA e1 = null; double r1 = 0, r2 = 0;

e1 = new EquationA(1, -14, -3);

System.out.println(e1.toString()); if (e1.delta > 0) { System.out.println(\两个根\ r1=e1.getRoot1(); r2=e1.getRoot2(); System.out.println(r1); System.out.println(r2); } else if (e1.delta == 0) { System.out.println(\相同根\ System.out.println(e1.getRoot2()); } else System.out.println(\无根\

EquationA e2 = new EquationA(11, 114, 3); System.out.println(e2);

2.矩形、圆形(一)

Circle(圆类):

public class Circle {

double x,y,r;

public Circle(double x,double y,double r) { this.x = x; this.y = y; this.r =r; }

public double GetPerimeter() { double perimeter=0; perimeter = 2*r*3.14; return perimeter; }

public double GetArea() { double area=0;

area=3.14*r*r; return area; }

public boolean Inside(double x1, double y1) { boolean b; double d; d=(x1-this.x)*(x1-this.x)+(y1-this.y)*(y1-this.y); b = (d>r*r) ? false : true; return b; }

public void CompareCirclesArea(Circle o2) { double s1,s2; s1=this.GetArea(); s2=o2.GetArea(); if (s1>s2) { System.out.println(\圆形1面积更大\ } else if (s2>s1) { System.out.println(\圆形2面积更大\ } else { System.out.println(\两个圆形面积一样大\ } }

public void CompareCirclesPeri(Circle o2) { double s1,s2; s1=this.GetPerimeter(); s2=o2.GetPerimeter(); if (s1>s2) { System.out.println(\圆形1周长更大\ } else if (s2>s1) { System.out.println(\圆形2周长更大\ }

else {

System.out.println(\两个圆形周长一样大\

} } }

Rect(矩形):

//define a class for Rectangles public class Rect {

double x1,y1,x2,y2; // left lower angle and right upper angle point define the location double width,length;

public Rect (double x1, double y1, double x2, double y2) { this.x1=x1; this.y1=y1; this.x2=x2; this.y2=y2; length = this.x2-this.x1; width = this.y2-this.y1; //没有分情况讨论,默认右上角点坐标大于左下角坐标 }

public double GetPerimeter() { double perimeter=0; perimeter = (length+width)*2; return perimeter; }

public double GetArea() { double area=0; area=length*width; return area; }

public Rect MergeRect(Rect r1) { double u1,v1,u2,v2; u1 = (r1.x1this.x2) ? r1.x2 : this.x2; v2 = (r1.y2>this.y2) ? r1.y2 : this.y2; Rect r2=new Rect(u1,v1,u2,v2); return r2; }

联系客服:779662525#qq.com(#替换为@)