2-1 类的创建

创建一个简单的表示矩形的Rectangle类,满足以下条件:
1、定义两个成员变量height和width,表示矩形的长和宽,类型为整型 2、定义一个getArea方法,返回矩形的面积 3、定义一个getPerimeter方法,返回矩形的周长 4、在main函数中,利用输入的2个参数分别作为矩形的长和宽,调用getArea和getPermeter方法,计算并返回矩形的面积和周长

输入:
输入2个正整数,中间用空格隔开,分别作为矩形的长和宽,例如:5 8

输出:
输出2个正整数,中间用空格隔开,分别表示矩形的面积和周长,例如:40 26

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int height = in.nextInt();
        int width = in.nextInt();
        Rectangle r = new Rectangle(height, width);
        System.out.println(r.getArea() + " " + r.getPermeter());
    }
}

class Rectangle{
    int height;
    int width;
    Rectangle(int h, int w){
        height = h;
        width = w;
    }
    int getArea() {
        return height * width;
    }
    int getPermeter() {
        return height * 2 + width * 2;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_31474267/article/details/81038281
2-1