如何在Java中创建一个矩形类,并通过set()传入长与宽,计算矩形的周长与面积并通过get()查看计算结果

创建名为Rec的package

创建Rectangle类,在该类中包含矩形的长与宽(width&length)

private double width;
private double length;

可传入wide与length的 set函数

public void set(double wide, double length){
        this.length = length;
        this.width = wide;

计算面积的area()

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

计算周长的perimeter()输出计算结果的get函数

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

public void get(){
        System.out.println("area = " + area());
        System.out.println("perimeter = " + perimeter());
    }

考虑到长与宽有可能不是整数,应将width length定义为double类型

然后就可以在main()中叫出你的对象了,假如你想要你的女朋友叫做r

Rectangle r = new Rectangle();
因为没有使用构造函数,而是用set函数传入width&length,所以别忘了double width,length。在main()中我们暂且叫它们x,y,并将他们传入set函数中

double x, y;
System.out.println("input wide and length here: ");
Scanner in = new Scanner(System.in);
x = in.nextDouble();
y = in.nextDouble();
r.set(x,y);
这样就基本完成了步骤

如果想查看计算结果别忘了添加get

r.get();
okokokokokokokokokokokokokokokokokokokokokokokokokokokokokokokokokokokokokokokokokok

*******当然这个程序还有一个小小的瑕疵,试试自己努力解决哦

完整的代码在此

package Rec;

import com.sun.org.apache.regexp.internal.RE;

import java.util.Scanner;

public class Rectangle {

    private double width;
    private double length;

    public double area(){
        double s;
        s = width * length;
        return s;
    }
    public double perimeter(){
        double c;
        c = (width + length) * 2;
        return c;
    }
    public void set(double width, double length){
        this.length = length;
        this.width = width;
    }
    public void get(){
        System.out.println("area = " + area());
        System.out.println("perimeter = " + perimeter());
    }
    public static void main(String [] args){
        double x,y;
        Scanner in = new Scanner(System.in);
        Rectangle r = new Rectangle();
        System.out.println("input wide and length here: ");
        x = in.nextDouble();
        y = in.nextDouble();
        r.set(x,y);
        r.get();
    }
}

你可能感兴趣的:(Java入门)