设计一个矩形类Rectangle

编写一个Java应用程序,该程序包含两个类,类的定义如下:

(1) 一个有关计算矩形面积的类Rectangle,定义如下成员:
① 两个私有的成员变量:length(长,double类型)、width(宽,double类型);
② 一个公有的无参数的构造方法,该构造方法将所有成员变量初始化为零;
③ 一个公有的有参数的方法void setXY(double a, double b),该方法用于设置矩形的属性length与width;
④ 一个公有的无参数的方法double getArea( ),该方法计算并返回矩形的面积;
⑤一个公有的无参数的方法double getPerimeter( ),该方法计算并返回矩形的周长;

(2) 一个测试类Main,在main方法中声明1个Rectangle类的对象rect,通过setXY方法给rect的属性length和width进行赋值(从键盘输入),通过getArea方法来计算rect的面积,通过getPerimeter方法来计算rect的周长,然后输出其面积与周长。

输入格式:

输入两个数,作为矩形的长、宽。

输出格式:

第一行输出矩形的面积。
第二行输出矩形的周长。

输入样例:

3.5  2

输出样例:

面积为7.0
周长为11.0

解析

 

import java.util.Scanner;

abstract class Person {
    public int id;
    public String name;
    public int bir;

    public Person(int id, String name, int bir) {
        this.id = id;
        this.name = name;
        this.bir = bir;
    }
}

class Student extends Person{
    public String major;
    public double score;

    public Student(int id, String name, int bir, String major, double score) {
        super(id, name, bir);
        this.major = major;
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student [" +
                "id=" + id +
                ", name=" + name + 
                ", bir=" + bir +
                ", major=" + major +
                ", score=" + score +
                ']';
    }
}
class Teacher extends Person{
    public String title;
    public double salary;

    public Teacher(int id, String name, int bir, String title, double salary) {
        super(id, name, bir);
        this.title = title;
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Teacher [" +
                "id=" + id +
                ", name=" + name + 
                ", bir=" + bir +
                ", title=" + title + 
                ", salary=" + salary +
                ']';
    }
}
public class Main {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        int n= scanner.nextInt();
        for (int i = 0; i <n ; i++) {
            int a= scanner.nextInt();
            int b= scanner.nextInt();
            String name= scanner.next();
            int bir= scanner.nextInt();
            String major= scanner.next();
            double score= scanner.nextDouble();
            if(a==0){
                Student student=new Student(b,name,bir,major,score);
                System.out.println(student);
            }
            else {
                Teacher teacher=new Teacher(b,name,bir,major,score);
                System.out.println(teacher);
            }
        }
    }
}

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值