第5次作业--对象的创建与使用

一、题目

  题目:编写程序,定义一个矩形类,具有长、宽、面积、周长共四个成员变量,计算面积和计算周长的两个方法,在主类中创建矩形对象,输入长和宽,输出矩形的面积和周长。

二、代码

import java.util.Scanner;

public class Ractrangle {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入第一个数:");
        int a = sc.nextInt();
        System.out.println("请输入第二个数:");
        int b = sc.nextInt();
        Triangle t = new Triangle(a, b);
        System.out.println("面积" + t.getArea() + "周长" + t.getLength());
    }
}

class Triangle {
    int a;
    int b;
    int area;
    int length;

    public Triangle(int a, int b) {
        // TODO Auto-generated constructor stub
        this.a = a;
        this.b = b;
    }

    public int getA() {
        return a;
    }

    public void setA(int a) {
        this.a = a;
    }

    public int getB() {
        return b;
    }

    public void setB(int b) {
        this.b = b;
    }

    public int getArea() {
        return area = a * b;
    }

    public int getLength() {
        return length = 2 * (a + b);
    }

}

三、运行结果

原文地址:https://www.cnblogs.com/himurayaiba/p/11543838.html