JAVA程式設計

Design andimplement a calss called Sphere that contains instance data that represents the sphere's diameter.Define the Sphere constructor to accept and initialize the diameter,and include getter and setter methods for the diameter.Include method that calculate and return the volume and surface area of the sphere.Include a toString method that returns a one-line description of the sphere.Great a driver class called MultiSphere,whose main method instantiates and updates several Sphere objects.

麻煩告訴我該怎麼寫??

Update:

請問ㄧ下,如果是要自己輸入半徑,那程式該如何修改?

謝謝!!

Update 2:

this.diameter = diameter;

這ㄧ行是什麼意思?如果不用this,那程式該怎麼修改呢?

謝~~

1 Answer

Rating
  • 1 decade ago
    Favorite Answer

    public class Sphere {

    private double diameter;

    public Sphere(float diameter){

    this.diameter = diameter;

    }

    public double getDiameter() {

    return diameter;

    }

    public void setDiameter(float diameter) {

    this.diameter = diameter;

    }

    public double getVolume(){

    return 4 / 3 * Math.PI * Math.pow(this.diameter, 3);

    }

    public double getSurface(){

    return 4 * Math.PI * Math.pow(this.diameter, 2);

    }

    public String toString() {

    return "Sphere -- Diameter is " this.diameter;

    }

    }

    public class MultiSphere {

    public static void main(String[] args) {

    Sphere s1 = new Sphere(3);

    System.out.println("s1 diameter is "+s1.getDiameter());

    System.out.println("s1 surface is "+s1.getSurface());

    System.out.println("s1 volumn is "+s1.getVolume());

    s1.setDiameter(4);

    System.out.println("s1 diameter is "+s1.getDiameter());

    System.out.println("s1 surface is "+s1.getSurface());

    System.out.println("s1 volumn is "+s1.getVolume());

    }

    }

Still have questions? Get your answers by asking now.