Java程序设计实验二 面向对象程序设计

[1]实验目的:通过编程和上机实验,掌握类和构造方法的定义及创建对象的方法,掌握类的封装及继承原则,正确使用重载和覆盖等多态概念设计可复用方法,熟悉包、接口的使用方法,掌握面向对象的程序设计方法。

[2]实验内容:

1、编写MyDate类,完善上次实验中的人员信息录入,实现日期合法性判断,包括大小月和闰年

package experiment2;

import java.util.ArrayList;
import java.util.Scanner;

class MyDate{
    int year;
    int month;
    int day;
    MyDate(int y,int m,int d)
    {
        year=y;month=m;day=d;
    }

    boolean isValidYear()
    {
        if(this.year<0||this.year>2021)return false;
        else return true;
    }

    boolean isValidMonth()
    {
        if(this.month<1||this.month>12)return false;
        else return true;
    }

    public boolean isValidDay()
    {
        if(this.day<1||this.day>DaysOfMonth())return false;
        else return true;
    }

    public boolean isLeapYear()
    {
        if(this.year%400==0||this.year%100!=0&&this.year%4==0)return true;
        else return false;
    }

    public int DaysOfMonth()
    {
        switch(this.month) {
            case 1:case 3:case 5:case 7:case 8:case 10: case 12:
                return 31;
            case 4:case 6:case 9:case 11:
                return 30;
            case 2:
                if(isLeapYear())return 29;
                else return 28;
            default: return -1;
        }
    }

    public boolean isValidDate()
    {
        if(isValidYear()&&isValidMonth()&&isValidDay())
            return true;
        else
            return false;

    }
}
class Stu extends MyDate{
    String name;
    int age;
    float score;
    Stu(String name, int year, int month, int day, float score){
        super(year,month,day);
        this.name=name;
        this.age=2021-year;
        this.score=score;
    }
    public void getInfo(){
        System.out.println("学生信息如下:\n姓名:" + this.name + " 出生日期:" + this.year + " " +this.month + " " + this.day +
                           " 年龄:" + this.age + " Java实验课成绩:" + this.score);
    }
}
public class Exp2_1 {
    public static void main(String[] args){
        String name;
        int year,month,day;
        float score;
        ArrayList<Stu> stu = new ArrayList<Stu>();
        System.out.println("请输入10位学生的姓名、出生年月日、java课程实验成绩\n");
        for(int i=0;i<10;i++){
            Scanner ss=new Scanner(System.in);
            name = ss.next();
            year = ss.nextInt();
            month = ss.nextInt();
            day = ss.nextInt();
            score = ss.nextFloat();
            stu.add(new Stu(name,year,month,day,score));
            if (!stu.get(i).isValidDate()){
                System.out.println("日期信息有误,重新输入:");
                stu.remove(i);
                i--;
            }
            else {
                stu.get(i).getInfo();
                if(stu.get(i).isLeapYear())
                    System.out.println("生日在闰年");
                else stu.get(i).isLeapYear();
                    System.out.println("生日不在闰年");
                if(stu.get(i).DaysOfMonth()==31)
                    System.out.println("生日在大月");
                else if (stu.get(i).DaysOfMonth()==30)
                    System.out.println("生日在小月");
                else System.out.println("生日既不在大月,也不在小月");
            }

        }
    }
}

 

 

 

*2、声明一个Person类和派生类Student,成员变量包括学号、姓名、入学时间、身份证号、学分绩点等信息,成员方法包括开户、存款、取款、查询(余额、明细)、销户等操作。

package experiment2;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Objects;
import java.util.Scanner;

class Person{
    String name;
    String id;
    MyDate birthday;
    int age;
    Person(String name, String id, int year, int month, int day){
        this.name=name;
        this.id=id;
        this.age=2021-year;
        birthday = new MyDate(year,month,day);
    }
}

class Student extends Person{
    String stu_id;
    MyDate time_of_enrollment;
    float score;
    int balance=0;
    StringBuffer log = new StringBuffer();
    Student(String name, String id, int year, int month, int day, String stu_id, MyDate time_of_enrollment, float score) {
        super(name, id, year, month, day);
        this.stu_id=stu_id;
        this.score=score;
        this.time_of_enrollment=time_of_enrollment;
    }
    public StringBuffer getLog(){
        return log;
    }
    public void deposit(int num){
        this.balance+=num;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        this.log.append(df.format(new Date())).append("存款").append(num).append("元,余额").append(this.balance).append("元\n");
    }
    public void withdraw(int num){
        if(balance-num>0){
            this.balance-=num;
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            this.log.append(df.format(new Date())).append("取款").append(num).append("元,余额").append(this.balance).append("元\n");
        }
        else
            System.out.println("余额不足,无法取款");
    }
    @Override
    public boolean equals(Object o){
        if(this==o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return stu_id.equals(student.stu_id);
    }
}

class Account{
    ArrayList<Student> account_list = new ArrayList<>();
    public void add_account(Student s){
        account_list.add(s);
    }
    public void delete_account(Student s){
        account_list.remove(s);
    }
    public Student getItem(int index){
        if(index<account_list.size())
            return account_list.get(index);
        else return null;
    }
    public int search(String id){
        for(int index=0;index<account_list.size();index++){
            if (Objects.equals(account_list.get(index).id, id))
                    return index;
        }
        return -1;
    }
}
class Exp2_2_ {
    Account account = new Account();
    public void main(){
        while (true){
            System.out.println("1、开户\n2、销户\n3、查询余额和明细\n4、存款\n5、取款\n按0退出");
            Scanner scanner=new Scanner(System.in);
            int key = scanner.nextInt();
            switch (key) {
                case 0 -> System.exit(0);
                case 1 -> {
                    System.out.println("依次输入依次学生姓名,身份证号,生日,学号,入学日期和成绩绩点:");
                    //Scanner scanner=new Scanner(System.in);
                    String name = scanner.next();
                    String id = scanner.next();
                    int year1 = scanner.nextInt();
                    int month1 = scanner.nextInt();
                    int day1 = scanner.nextInt();
                    String s_id = scanner.next();
                    int year2 = scanner.nextInt();
                    int month2 = scanner.nextInt();
                    int day2 = scanner.nextInt();
                    float score = scanner.nextFloat();
                    MyDate date = new MyDate(year2, month2, day2);
                    Student student = new Student(name, id, year1, month1, day1, s_id, date, score);
                    account.add_account(student);
                    System.out.println("创建成功");
                }
                case 2 -> {
                    System.out.println("输入学生身份证号:");
                    String id_to_delete = scanner.next();
                    int index = account.search(id_to_delete);
                    Student s = account.getItem(index);
                    if (index != -1)
                        account.delete_account(s);
                    else System.out.println("账户不存在");
                }
                case 3 -> {
                    System.out.println("输入学生身份证号:");
                    String id_to_search = scanner.next();
                    int index2 = account.search(id_to_search);
                    if (index2 == -1)
                        System.out.println("账户不存在");
                    else {
                        Student s1 = account.getItem(index2);
                        StringBuffer log = s1.getLog();
                        System.out.println(log);
                    }
                }
                case 4 -> {
                    System.out.println("输入学生身份证号:");
                    String id_to_deposit = scanner.next();
                    int index3 = account.search(id_to_deposit);
                    if (index3 == -1)
                        System.out.println("账户不存在");
                    else {
                        Student s2 = account.getItem(index3);
                        System.out.println("输入存款金额:");
                        int num = scanner.nextInt();
                        s2.deposit(num);
                    }
                }
                case 5 -> {
                    System.out.println("输入学生身份证号:");
                    String id_to_withdraw = scanner.next();
                    int index4 = account.search(id_to_withdraw);
                    if (index4 == -1)
                        System.out.println("账户不存在");
                    else {
                        Student s3 = account.getItem(index4);
                        System.out.println("输入存款金额:");
                        int num = scanner.nextInt();
                        s3.withdraw(num);
                    }
                }
            }
        }
    }
}

public class Exp2_2 {
    public static void main(String[] args){
        Exp2_2_ run = new Exp2_2_();
        run.main();
    }
}

 

 

 

*3、设计一个汽车类Vehicle,包含的属性有车轮个数(wheels)和车重(weight)。小车类Car是Vehicle类的子类,其中包含的属性有载人数(loader)。卡车类(Truck类)是Car类的子类,其中包含的属性有载重量(payload)。每一个类都有相关数据的输出。

实验要求:(1)汽车类Vehicle的构造方法带有2个参数,分别是wheels和weight。Car类的构造方法带有3个参数,分别为wheels、weight和loader。Truck的构造方法带有4个参数,分别为wheels、weight、loader和payload。

package experiment2;

import java.util.Scanner;

class Vehicle{
    private int wheels;
    private float weight;
    Vehicle(int wheels, float weight){
        this.wheels=wheels;
        this.weight=weight;
    }
    public int getWheels(){
        return this.wheels;
    }
    public float getWeight(){
        return this.weight;
    }
}

class Car extends Vehicle{
    private int loader;
    Car(int wheels, float weight, int loader){
        super(wheels,weight);
        this.loader=loader;
    }
    public int getLoader(){
        return this.loader;
    }
}

class Truck extends Vehicle{
    private int loader;
    private float payload;
    Truck(int wheels, float weight, int loader, float payload){
        super(wheels,weight);
        this.loader=loader;
        this.payload=payload;
    }
    public int getLoader(){
        return this.loader;
    }
    public float getPayload(){
        return this.payload;
    }
}
public class Exp2_3 {
    public static void main(String[] args){
        System.out.println("输入wheels,weight,loader,payload:");
        Scanner scanner = new Scanner(System.in);
        int wheels,loader;
        float weight, payload;
        wheels=scanner.nextInt();
        weight=scanner.nextFloat();
        loader=scanner.nextInt();
        payload=scanner.nextFloat();
        Vehicle vehicle=new Vehicle(wheels,weight);
        System.out.println("vehicle wheels: " + vehicle.getWheels() + " vehicle weight: " + vehicle.getWeight());
        Car car = new Car(wheels,weight,loader);
        System.out.println("car wheel: " + car.getWheels() + " car weight: " + car.getWeight() + " car loader: " + car.getLoader());
        Truck truck = new Truck(wheels,weight,loader,payload);
        System.out.println("truck wheel: " + truck.getWheels() + " truck weight: " + truck.getWeight() + " truck loader: " + truck.getLoader()
                           + " truck payload: " + truck.getPayload());
    }
}

 

4、定义接口Shape及其抽象方法getArea()和getPerimeter()用于计算图形和面积和周长。定义类Rectangle(矩形)、类Circle(圆形)、类Triangle(三角形),要求这些类继承点类Coordinates()并实现接口的抽象方法。

package experiment2;
import java.util.*;
interface Shape
{
    public abstract double getArea();
    public abstract double getPerimeter();
}
class Coordinate
{
    long x=0;
    long y=0;
    Coordinate(long x,long y)
    {
        this.x=x;
        this.y=y;
    }
    Coordinate() {}
    public void get_position(){
        System.out.println("["+x+","+y+"]");;
    }
}
class Rectangle extends Coordinate implements Shape
{
    double length;
    double width;
    Rectangle(double length,double width,long x,long y)
    {
        super(x,y);
        this.length=length;
        this.width=width;
    }
    public double getArea()
    {
        return length*width;
    }
    public double getPerimeter()
    {
        return 2*(length+width);
    }
}
class Circle extends Coordinate implements Shape
{
    double radius;
    Circle(double radius,long x,long y)
    {
        super(x,y);
        this.radius=radius;
    }
    public double getArea()
    {
        return Math.PI*radius*radius;
    }
    public double getPerimeter()
    {
        return Math.PI*2*radius;
    }
}
class Triangle extends Coordinate implements Shape
{
    double length1,length2,length3;
    Coordinate c1,c2,c3;
    Triangle(double len1,double len2,double len3,long x1,long y1,long x2,long y2,long x3,long y3)
    {
        length1=len1;
        length2=len2;
        length3=len3;
        c1=new Coordinate(x1,y1);
        c2=new Coordinate(x2,y2);
        c3=new Coordinate(x3,y3);
    }
    public double getPerimeter()
    {
        return length1+length2+length3;
    }
    public double getArea()
    {
        double p=(length1+length2+length3)/2;
        return Math.sqrt(p*(p-length1)*(p-length2)*(p-length3));
    }
}

public class Exp2_4 {
    public static void main(String[] args)
    {
        Scanner scanner=new Scanner(System.in);
        while(true)
        {
            System.out.println("请进行选择\n1:矩形   2:圆形   3:三角形   其他数字:退出");
            int aa=scanner.nextInt();
            switch (aa) {
                case 1 -> {
                    System.out.println("请输入矩形的长、宽与左上角顶点坐标:");
                    double length = scanner.nextDouble();
                    double width = scanner.nextDouble();
                    long x = scanner.nextLong();
                    long y = scanner.nextLong();
                    Rectangle rec = new Rectangle(length, width, x, y);
                    System.out.println("该矩形的位置为:");rec.get_position();
                    System.out.println("面积为:" + rec.getArea());
                    System.out.println("周长为:" + rec.getPerimeter());
                }
                case 2 -> {
                    System.out.println("请输入圆的半径与原点坐标:");
                    double radius = scanner.nextDouble();
                    long x = scanner.nextLong();
                    long y = scanner.nextLong();
                    Circle cir = new Circle(radius, x, y);
                    System.out.println("该圆的位置为:");cir.get_position();
                    System.out.println("面积为:" + cir.getArea());
                    System.out.println("周长为:" + cir.getPerimeter());
                }
                case 3 -> {
                    System.out.println("请输入三角形的三条边长和三个顶点的坐标:");
                    double len1 = scanner.nextDouble();
                    double len2 = scanner.nextDouble();
                    double len3 = scanner.nextDouble();
                    long x1 = scanner.nextLong();
                    long y1 = scanner.nextLong();
                    long x2 = scanner.nextLong();
                    long y2 = scanner.nextLong();
                    long x3 = scanner.nextLong();
                    long y3 = scanner.nextLong();
                    Triangle tri = new Triangle(len1, len2, len3, x1, y1, x2, y2, x3, y3);
                    System.out.println("该三角形三个顶点坐标为:");
                    tri.c1.get_position();
                    tri.c2.get_position();
                    tri.c3.get_position();
                    System.out.println("面积为:" + tri.getArea());
                    System.out.println("周长为:" + tri.getPerimeter());
                }
                default -> System.exit(0);
            }
        }
    }
}

[3]实验分析

掌握了Java中类和构造方法的定义及创建对象的方法,能够通过继承,封装,实现接口等方法实现面向对象编程。

  • 7
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ace2NoU

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值