JAVA高手来帮帮忙啦,两道编程题。悬赏30分。在线等!!!

1个回答

  • 第一题:

    public class Complex {

    private double real;// 实部

    private double imagin;// 虚部

    // 重载默认构造方法

    public Complex() {

    real = 0;

    imagin = 0;

    }

    // 有参构造方法

    public Complex(double real, double imagin) {

    this.real = real;

    this.imagin = imagin;

    }

    // 获取实部

    public double getReal() {

    return real;

    }

    // 获取虚部

    public double getImagin() {

    return imagin;

    }

    // 虚数相加

    public Complex complexAdd(Complex number) {

    return new Complex(this.getReal() + number.getReal(), this.getImagin()

    + number.getImagin());

    }

    // 虚数想减

    public Complex complexMinus(Complex number) {

    return new Complex(this.getReal() - number.getReal(), this.getImagin()

    - number.getImagin());

    }

    // 虚数想乘

    public Complex complexMulti(Complex number) {

    return new Complex(this.getReal() * number.getReal(), this.getImagin()

    * number.getImagin());

    }

    //重载toString

    public String toString() {

    return ""+real+"+"+imagin+"i";

    }

    public static void main(String[] args) {

    //测试桩

    Complex c1 = new Complex(2,3);

    Complex c2 = new Complex(4,6);

    //测试加法

    System.out.println(c1.complexAdd(c2));

    //减法

    System.out.println(c1.complexMinus(c2));

    //乘法

    System.out.println(c1.complexMulti(c2));

    //toString验证

    Complex c = new Complex(2,3);

    System.out.println(c);

    }

    }

    第二题:

    1. 抽象父类Shape:

    //父类接口

    public abstract class Shape {

    public double getSquare(){

    return 0;

    }

    }

    2. 三角形子类

    public class Triangle extends Shape {

    private double a;// 三角形底边长度

    private double h;// 三角形的高

    // 构造方法

    public Triangle(double a, double h) {

    this.a = a;

    this.h = h;

    }

    // 三角形面积

    public double getSquare() {

    return a * h / 2;

    }

    }

    3.正方形子类

    public class Square extends Shape {

    private double a;// 正方形边长

    // 构造方法

    public Square(double a) {

    this.a = a;

    }

    public double getSquare() {

    return a*a;

    }

    }

    3.圆形子类

    public class Circle extends Shape {

    public static final double PI = 3.14;

    private double r;// 圆形半径

    // 构造方法

    public Circle(double r) {

    this.r = r;

    }

    public double getSquare() {

    return PI*r*r;

    }

    }

    4. 测试桩主方法:

    //测试桩主方法

    public class TestShape {

    public static void main(String[] args) {

    //三角形实现

    Triangle t = new Triangle(2,2);

    System.out.println(t.getSquare());

    //正方形实现

    Square s = new Square(3);

    System.out.println(s.getSquare());

    //圆形实现

    Circle c = new Circle(4);

    System.out.println(c.getSquare());

    }

    }