Java程序设计2023-第三次上机练习

这篇具有很好参考价值的文章主要介绍了Java程序设计2023-第三次上机练习。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

这次的练习主要是一些类的高阶操作,像继承、接口和内部类这些,但其实还是挺简单的

 

目录

7-1 jmu-Java-03面向对象基础-04-形状-继承

前言

本题描述

思考

输入样例:

输出样例:

 7-3 jmu-Java-04面向对象进阶-03-接口-自定义接口ArrayIntegerStack

main方法说明

思考

输入样例

输出样例

 7-3 教师类

输入格式:

输出格式:

输入样例:

输出样例:

 7-4 教师类-2

输入格式:

输出格式:

输入样例:

输出样例:

 7-5 编写一个类Shop(商店)、内部类InnerCoupons(内部购物券)

输入格式:

输出格式:

输入样例:

输出样例:

7-6 jmu-Java-04面向对象进阶-01-接口-Comparable

1.编写PersonSortable类

2.main方法中

输入样例:

输出样例:

 7-7 jmu-Java-03面向对象-06-继承覆盖综合练习-Person、Student、Employee、Company

main方法说明

输入样例:

输出样例:

 7-8 定义接口(Biology、Animal)、类(Person)、子类(Pupil)

输入格式:

输出格式:

输入样例:

输出样例:

7-9 Employee类的层级结构

输入格式:

输出格式:

输入样例:

输出样例:


7-1 jmu-Java-03面向对象基础-04-形状-继承

前言

前面题目形状中我们看到,为了输出所有形状的周长与面积,需要建立多个数组进行多次循环。这次试验使用继承与多态来改进我们的设计。

本题描述

1.定义抽象类Shape
属性:不可变静态常量double PI,值为3.14
抽象方法:public double getPerimeter(),public double getArea()

2.RectangleCircle类均继承自Shape类。
Rectangle类(属性:int width,length)、Circle类(属性:int radius)。
带参构造方法为Rectangle(int width,int length),Circle(int radius)
toString方法(Eclipse自动生成)

3.编写double sumAllArea方法计算并返回传入的形状数组中所有对象的面积和
double sumAllPerimeter方法计算并返回传入的形状数组中所有对象的周长和

4.main方法
4.1 输入整型值n,然后建立n个不同的形状。如果输入rect,则依次输入宽、长。如果输入cir,则输入半径。
4.2 然后输出所有的形状的周长之和,面积之和。并将所有的形状信息以样例的格式输出。 提示:使用Arrays.toString
4.3 最后输出每个形状的类型与父类型.使用类似shape.getClass() //获得类型, shape.getClass().getSuperclass() //获得父类型;

注意:处理输入的时候使用混合使用nextIntnextLine需注意行尾回车换行问题。

思考

  1. 你觉得sumAllArea和sumAllPerimeter方法放在哪个类中更合适?
  2. 是否应该声明为static?

输入样例:

4
rect
3 1
rect
1 5
cir
1
cir
2

输出样例:

38.84
23.700000000000003
[Rectangle [width=3, length=1], Rectangle [width=1, length=5], Circle [radius=1], Circle [radius=2]]
class Rectangle,class Shape
class Rectangle,class Shape
class Circle,class Shape
class Circle,class Shape

 

import java.math.*;
import java.util.*;


abstract class Shape{
    final double PI = 3.14;
    public abstract double getPerimeter();
    public abstract double getArea();
}

class Rectangle extends Shape{
    private int length = 0;
    private int width = 0;

    public Rectangle(int _length,int _width){
        this.length = _length;
        this.width = _width;
    }

    public double getArea(){
        return this.width * this.length;
    }

    public double getPerimeter(){
        return (this.width + this.length)*2;
    }

    public String toString(){
        return "Rectangle [width=" + this.length + ", length=" + this.width + "]";
    }
}

class Circle extends Shape{
    private int radius = 0;

    public Circle(int _radius){
        this.radius = _radius;
    }

    public double getPerimeter(){
        return this.radius * PI * 2;
    }

    public double getArea(){
        return this.radius * PI * this.radius;
    }

    public String toString(){
        return "Circle [radius=" + this.radius + "]";
    }
}

public class Main {

    static Scanner in = new Scanner(System.in);
    public static void main(String[] args) {
        int n = in.nextInt();
        ArrayList<Shape> shape = new ArrayList<Shape>();
        double sumArea = 0;
        double sumPerimeter = 0;
        for(int i=0;i<n;i++){
            String op = in.next();
            if(op.equals("rect")){
                int width = in.nextInt();
                int length = in.nextInt();
                shape.add(new Rectangle(width,length));
            }
            if(op.equals("cir")){
                int radius = in.nextInt();
                shape.add(new Circle(radius));
            }
        }  
        for(int i=0;i<n;i++){
            sumArea += shape.get(i).getArea();
            sumPerimeter += shape.get(i).getPerimeter(); 
        }
        System.out.println(sumPerimeter);
        System.out.println(sumArea);
        System.out.println(shape.toString());
        for(int i=0;i<n;i++){
            System.out.println(shape.get(i).getClass() + "," + shape.get(i).getClass().getSuperclass());
        }
    }
}

 7-3 jmu-Java-04面向对象进阶-03-接口-自定义接口ArrayIntegerStack

定义IntegerStack接口,用于声明一个存放Integer元素的栈的常见方法:

 

public Integer push(Integer item); //如果item为null,则不入栈直接返回null。如果栈满,也返回null。如果插入成功,返回item。 public Integer pop(); //出栈,如果为空,则返回null。出栈时只移动栈顶指针,相应位置不置为null public Integer peek(); //获得栈顶元素,如果为空,则返回null. public boolean empty(); //如果为空返回true public int size(); //返回栈中元素个数

定义IntegerStack的实现类ArrayIntegerStack,内部使用数组实现。创建时,可指定内部数组大小。

main方法说明

  1. 输入n,建立可包含n个元素的ArrayIntegerStack对象
  2. 输入m个值,均入栈。每次入栈均打印入栈返回结果。
  3. 输出栈顶元素,输出是否为空,输出size
  4. 使用Arrays.toString()输出内部数组中的值。
  5. 输入x,然后出栈x次,每次出栈均打印。
  6. 输出栈顶元素,输出是否为空,输出size
  7. 使用Arrays.toString()输出内部数组中的值。

思考

如果IntegerStack接口的实现类内部使用ArrayList来存储元素,怎么实现?测试代码需要进行什么修改?

输入样例

5
3
1 2 3
2

输出样例

1
2
3
3,false,3
[1, 2, 3, null, null]
3
2
1,false,1
[1, 2, 3, null, null]
import java.math.*;
import java.util.*;

interface IntegerStack{
    public Integer push(Integer item);
    public Integer pop();   
    public Integer peek(); 
    public boolean empty();
    public int size();     
}

class ArrayIntegerStack implements IntegerStack{

    Integer[] array;
    int len = 0;
    int length = 0;

    public ArrayIntegerStack(int _len){
        this.array = new Integer[_len];
        this.length = _len;
    }

    public Integer push(Integer item){
        if(this.array == null){
            return null;
        }
        if(this.len == this.length){
            return null;
        }
        array[this.len] = item;
        this.len++;
        return item;
    }

    public Integer pop(){
        if(this.len == 0){
            return null;
        }
        this.len--;
        return this.array[this.len];
    }  
    public Integer peek(){
        if(this.len == 0){
            return null;
        }
        return this.array[this.len-1];
    }  
    public boolean empty(){
        if(this.len == 0){
            return true;
        }
        return false;
    } 
    public int size(){
        return this.len;
    }

    public String toString(){
        String res = "[";
        for(int i=0;i<length - 1;i++){
            res += this.array[i];
            res += ", ";
        }
        res += this.array[this.length - 1];
        res += "]";
        return res;
    }
}

public class Main {
    static Scanner in = new Scanner(System.in);
    public static void main(String[] args) {     
        int n = in.nextInt();
        ArrayIntegerStack ais = new ArrayIntegerStack(n);
        int m = in.nextInt();
        for(int i=0;i<m;i++){
            int tmp = in.nextInt();
            System.out.println(ais.push(tmp));
        }
        System.out.println(ais.peek() + "," + ais.empty() + "," + ais.size()); 
        System.out.println(ais.toString());
        int x = in.nextInt();
        for(int i=0;i<x;i++){
            System.out.println(ais.pop());
        }
        System.out.println(ais.peek() + "," + ais.empty() + "," + ais.size()); 
        System.out.println(ais.toString());
    }
}

 7-3 教师类

 

设计一个教师类Teacher,要求:
属性有编号(int no)、姓名(String name)、年龄(int age)、所属学院(String seminary),为这些属性设置相应的get和set方法。
为Teacher类重写equals方法,要求:当两个教师对象的no相同时返回true。
重写Teacher类的toString方法,通过该方法可以返回“no: , name:, age: **, seminary: **”形式的字符串。

输入格式:

两个教师对象的编号,姓名,年龄,学院

输出格式:

教师的信息
两个教师是否相等

输入样例:

在这里给出一组输入。例如:

1 Linda 38 SoftwareEngineering
2 Mindy 27 ComputerScience

输出样例:

在这里给出相应的输出。例如:

no: 1, name:Linda, age: 38, seminary: SoftwareEngineering
no: 2, name:Mindy, age: 27, seminary: ComputerScience
false

 

import java.math.*;
import java.util.*;

class Teacher{
    private int no;
    private String name;
    private int age;
    private String seminary;

    public Teacher(int _no,String _name,int _age,String _seminary){
        this.age = _age;
        this.name = _name;
        this.no = _no;
        this.seminary = _seminary;
    }

    public boolean equals(Teacher a){
        return this.age == a.age && this.no == a.no && this.seminary.equals(a.seminary) && this.name.equals(a.name);
    } 

    public String toString(){
        return "no: " + this.no + ", name:" + this.name + ", age: " + this.age + ", seminary: " + this.seminary;
    }
}

public class Main {

    static Scanner in = new Scanner(System.in);
    public static void main(String[] args) {
        int no = in.nextInt();
        String name = in.next();
        int age = in.nextInt();
        String seminary = in.next();

        Teacher t1 = new Teacher(no,name,age,seminary);

        no = in.nextInt();
        name = in.next();
        age = in.nextInt();
        seminary = in.next();

        Teacher t2 = new Teacher(no,name,age,seminary);

        System.out.println(t1.toString());
        System.out.println(t2);
        System.out.println(t1.equals(t2));
    }
}

 7-4 教师类-2

修改题目143

  1. 修改教师类,使得由多个Teacher对象所形成的数组可以排序(编号由低到高排序),并在main函数中使用Arrays.sort(Object[] a)方法排序
  2. 定义一个类TeacherManagement,包含教师数组,提供方法add(Teacher[]),使其可以添加教师,提供重载方法search,方法可以在一组给定的教师中,根据姓名或年龄返回等于指定姓名或年龄的教师的字符串信息,信息格式为:“no: , name:, age: **, seminary: **”。如果没有满足条件的教师,则返回“no such teacher”。

输入格式:

教师个数
教师信息
待查找教师的姓名
待查找教师的年龄

输出格式:

排序后的信息
按姓名查找的老师信息
按年龄查找的老师信息

输入样例:

在这里给出一组输入。例如:

4
3 Linda 38 SoftwareEngineering
1 Mindy 27 ComputerScience
4 Cindy 28 SoftwareEngineering
2 Melody 27 ComputerScience
Cindy
27

输出样例:

在这里给出相应的输出。例如:

no: 1, name: Mindy, age: 27, seminary: ComputerScience
no: 2, name: Melody, age: 27, seminary: ComputerScience
no: 3, name: Linda, age: 38, seminary: SoftwareEngineering
no: 4, name: Cindy, age: 28, seminary: SoftwareEngineering
search by name:
no: 4, name: Cindy, age: 28, seminary: SoftwareEngineering
search by age:
no: 1, name: Mindy, age: 27, seminary: ComputerScience
no: 2, name: Melody, age: 27, seminary: ComputerScience
import java.math.*;
import java.util.*;

class Teacher{
    private int no;
    private String name;
    private int age;
    private String seminary;

    public Teacher(int _no,String _name,int _age,String _seminary){
        this.age = _age;
        this.name = _name;
        this.no = _no;
        this.seminary = _seminary;
    }

    public int getAge(){
        return this.age;
    }

    public String getName(){
        return this.name;
    }

    public int getNo(){
        return this.no;
    }

    public boolean equals(Teacher a){
        return this.age == a.age && this.no == a.no && this.seminary.equals(a.seminary) && this.name.equals(a.name);
    } 

    public String toString(){
        return "no: " + this.no + ", name: " + this.name + ", age: " + this.age + ", seminary: " + this.seminary;
    }
}

class TeacherManagement{
    public ArrayList<Teacher> teachers = new ArrayList<Teacher>();

    public void add(Teacher t){
        this.teachers.add(t);
    }

    public void search(int _age){
        int flag = 1;
        System.out.println("search by age:");
        for(int i=0;i<teachers.size();i++){
            if(_age == teachers.get(i).getAge()){
                flag = 0;
                System.out.println(teachers.get(i));
            }
        }
        if(flag == 1){
            System.out.println("no such teacher");
        }
    }

    public void search(String _name){
        int flag = 1;
        System.out.println("search by name:");
        for(int i=0;i<teachers.size();i++){
            if(_name.equals(teachers.get(i).getName())){
                flag = 0;
                System.out.println(teachers.get(i));
            }
        }
        if(flag == 1){
            System.out.println("no such teacher");
        }
    }

    public void sort(){
        for(int i=0;i<teachers.size();i++){
            for(int j=0;j<teachers.size()-1;j++){
                if(teachers.get(i).getNo() < teachers.get(j).getNo()){
                    Teacher tmp = teachers.get(i);
                    teachers.set(i,teachers.get(j));
                    teachers.set(j,tmp);
                }
            }
        }
    }
}

public class Main {
    static Scanner in = new Scanner(System.in);
    public static void main(String[] args) {      
        int num = in.nextInt();
        TeacherManagement tm = new TeacherManagement();
        for(int i=0;i<num;i++){
            int no = in.nextInt();
            String name = in.next();
            int age = in.nextInt();
            String seminary = in.next();
            Teacher tmp = new Teacher(no,name,age,seminary);
            tm.add(tmp);
        }
        tm.sort();
        for(int i=0;i<tm.teachers.size();i++){
            System.out.println(tm.teachers.get(i));
        }
        String s = in.next();
        int nm = 0;
        try{
            nm = Integer.valueOf(s);
            tm.search(nm);
        } catch (Exception e){
            tm.search(s);
        }
        s = in.next();
        try{
            nm = Integer.valueOf(s);
            tm.search(nm);
        } catch (Exception e){
            tm.search(s);
        }
    }
}

 7-5 编写一个类Shop(商店)、内部类InnerCoupons(内部购物券)

 

编写一个类Shop(商店),该类中有一个成员内部类InnerCoupons(内部购物券),可以用于购买该商店的牛奶(假设每箱牛奶售价为50元)。要求如下:
(1)Shop类中有私有属性milkCount(牛奶的箱数,int类型)、公有的成员方法setMilkCount( )getMilkCount( )分别用于设置和获取牛奶的箱数。
(2)成员内部类InnerCoupons,有公有属性value(面值,int类型),一个带参数的构造方法可以设定购物券的面值value,一个公有的成员方法buy( )要求输出使用了面值为多少的购物券进行支付,同时使商店牛奶的箱数减少value/50。
(3)Shop类中还有成员变量coupons50(面值为50元的内部购物券,类型为InnerCoupons)、coupons100(面值为100元的内部购物券,类型为InnerCoupons)。
(4)在Shop类的构造方法中,调用内部类InnerCoupons的带参数的构造方法分别创建上面的购物券coupons50、coupons100。


在测试类Main中,创建一个Shop类的对象myshop,从键盘输入一个整数(大于或等于3),将其设置为牛奶的箱数。假定有顾客分别使用了该商店面值为50的购物券、面值为100的购物券各消费一次,分别输出消费后商店剩下的牛奶箱数。

输入格式:

输入一个大于或等于3的整数。

输出格式:

使用了面值为50的购物券进行支付
牛奶还剩XX箱
使用了面值为100的购物券进行支付
牛奶还剩XX箱

输入样例:

在这里给出一组输入。例如:

5

输出样例:

在这里给出相应的输出。例如:

使用了面值为50的购物券进行支付
牛奶还剩4箱
使用了面值为100的购物券进行支付
牛奶还剩2箱
import java.math.*;
import java.util.*;

class Shop{
    private int milkCount;
    public InnerCoupons coupons50 = new InnerCoupons(50);
    public InnerCoupons coupons100 = new InnerCoupons(100);

    public void setMilkCount(int nums){
        this.milkCount = nums;
    } 

    public int getMilkCount(){
        return this.milkCount;
    }

    public Shop(int nums){
        this.milkCount = nums;
    }

    public class InnerCoupons{
        public int value;

        public InnerCoupons(int _value){
            this.value = _value;
        }

        public void buy(){
            System.out.println("使用了面值为" + value + "的购物券进行支付");
            milkCount -= value/50;
            System.out.println("牛奶还剩" + milkCount + "箱");
        }
    }
}
public class Main {

    static Scanner in = new Scanner(System.in);
    public static void main(String[] args) {
        int n = in.nextInt();
        Shop shop = new Shop(n);
        shop.coupons50.buy();
        shop.coupons100.buy();
    }
}

7-6 jmu-Java-04面向对象进阶-01-接口-Comparable

 

编写实现Comparable接口的PersonSortable类,使其按name以及age排序

1.编写PersonSortable类

属性:private name(String)private age(int)
有参构造函数:参数为name,age
toString函数:返回格式为:name-age
实现Comparable接口:实现先对name升序排序,如果name相同则对age进行升序排序

2.main方法中

  1. 首先输入n
  2. 输入n行name age,并创建n个对象放入数组
  3. 对数组进行排序后输出。
  4. 最后一行使用System.out.println(Arrays.toString(PersonSortable.class.getInterfaces()));输出PersonSortable所实现的所有接口

输入样例:

5
zhang 15
zhang 12
wang 14
Wang 17
li 17

输出样例:

Wang-17
li-17
wang-14
zhang-12
zhang-15
//这行是标识信息
import java.math.*;
import java.util.*;

class PersonSortable implements Comparable<PersonSortable>{
    private String name;
    private int age;

    public String getName(){
        return this.name;
    }

    public int getAge(){
        return this.age;
    }

    public PersonSortable(String _name,int _age){
        this.name = _name;
        this.age = _age;
    }

    public String toString(){
        return this.name + "-" + this.age;
    }

    public int compareTo(PersonSortable person){
        if(this.name.equals(person.getName())){
            return this.age - person.getAge(); 
        }
        return this.name.compareTo(person.getName());
    }
}

public class Main {

    static Scanner in = new Scanner(System.in);
    public static void main(String[] args) {
        int n = in.nextInt();
        PersonSortable[] ps = new PersonSortable[n];
        for(int i=0;i<n;i++){
            String name = in.next();
            int age = in.nextInt();
            ps[i] = new PersonSortable(name,age);
        }
        Arrays.sort(ps);
        for(PersonSortable p : ps){
            System.out.println(p);
       }
        System.out.println(Arrays.toString(PersonSortable.class.getInterfaces()));
    }
}

 7-7 jmu-Java-03面向对象-06-继承覆盖综合练习-Person、Student、Employee、Company

 

定义Person抽象类,Student类、Company类,Employee类。

Person类的属性String name, int age, boolean gender
Person类的方法:

public Person(String name, int age, boolean gender);
public String toString();         //返回"name-age-gender"格式的字符串
public boolean equals(Object obj);//比较name、age、gender,都相同返回true,否则返回false

Student类继承自Person,属性:String stuNo, String clazz
Student类的方法:

//建议使用super复用Person类的相关有参构造函数
public Student(String name, int age, boolean gender, String stuNo, String clazz);
public String toString();         //返回 “Student:person的toString-stuNo-clazz”格式的字符串
public boolean equals(Object obj);//首先调用父类的equals方法,如果返回true,则继续比较stuNo与clazz。

Company类属性:String name
Company类方法:

public Company(String name);
public String toString();         //直接返回name
public boolean equals(Object obj);//name相同返回true

Employee类继承自Person,属性:Company company, double salary
Employee类方法:

//建议使用super复用Person类的相关有参构造函数
public Employee(String name, int age, boolean gender, double salary, Company company);
public String toString();         //返回"Employee:person的toString-company-salary"格式的字符串
public boolean equals(Object obj);//首先调用父类的equals方法,如果返回true。再比较company与salary。
//比较salary属性时,使用DecimalFormat df = new DecimalFormat("#.#");保留1位小数

编写equals方法重要说明:

  1. 对Employee的company属性的比较。要考虑传入为null的情况。如果company不为null且传入为null,返回false
  2. 对所有String字符类型比较时,也要考虑null情况。

提示

  1. 排序可使用Collections.sort
  2. equals方法要考虑周全

main方法说明

  1. 创建若干Student对象、Employee对象。
    输入s,然后依次输入name age gender stuNo clazz创建Student对象
    输入e,然后依次输入name age gender salary company创建Employee对象
    然后将创建好的对象放入List<Person> personList。输入其他字符,则结束创建。

创建说明: 对于String类型,如果为null则不创建对象,而赋值为null。对于company属性,如果为null则赋值为null,否则创建相应的Company对象。

  1. 对personList中的元素实现先按照姓名升序排序,姓名相同再按照年龄升序排序。提示:可使用Comparable<Person>Comparator<Person>

  2. 接受输入,如果输入为exitreturn退出程序,否则继续下面步骤。

  3. 将personList中的元素按照类型分别放到stuList与empList。注意:不要将两个内容相同的对象放入列表(是否相同是根据equals返回结果进行判定)。

  4. 输出字符串stuList,然后输出stuList中的每个对象。

  5. 输出字符串empList,然后输出empList中的每个对象。

1-3为一个测试点
4-6为一个测试点

输入样例:

s zhang 23 false 001 net15
e wang 18 true 3000.51 IBM
s zhang 23 false 001 net15
e bo 25 true 5000.51 IBM
e bo 25 true 5000.52 IBM
e bo 18 true 5000.54 IBM
e tan 25 true 5000.56 IBM
e tan 25 true 5000.51 IBM
s wang 17 false 002 null
s wang 17 false 002 null
e hua 16 false 1000 null
s wang 17 false 002 net16
e hua 16 false 1000 null
e hua 18 false 1234 MicroSoft
!
continue

输出样例:

Employee:bo-18-true-IBM-5000.54
Employee:bo-25-true-IBM-5000.51
Employee:bo-25-true-IBM-5000.52
Employee:hua-16-false-null-1000.0
Employee:hua-16-false-null-1000.0
Employee:hua-18-false-MicroSoft-1234.0
Employee:tan-25-true-IBM-5000.56
Employee:tan-25-true-IBM-5000.51
Student:wang-17-false-002-null
Student:wang-17-false-002-null
Student:wang-17-false-002-net16
Employee:wang-18-true-IBM-3000.51
Student:zhang-23-false-001-net15
Student:zhang-23-false-001-net15
stuList
Student:wang-17-false-002-null
Student:wang-17-false-002-net16
Student:zhang-23-false-001-net15
empList
Employee:bo-18-true-IBM-5000.54
Employee:bo-25-true-IBM-5000.51
Employee:hua-16-false-null-1000.0
Employee:hua-18-false-MicroSoft-1234.0
Employee:tan-25-true-IBM-5000.56
Employee:tan-25-true-IBM-5000.51
Employee:wang-18-true-IBM-3000.51
import java.math.*;
import java.util.*;
import java.text.*;


class Person implements Comparable<Person>{
    public String name;
    public int age;
    public boolean gender;

    public Person(String name, int age, boolean gender){
        this.name = name;
        this.gender = gender;
        this.age = age;
    }

    public String toString(){
        return this.name + "-" + this.age + "-" + this.gender;
    }       
    
    public boolean equals(Object obj){
        Person ob = (Person) obj;
        return this.name.equals(ob.name) && this.age == ob.age && this.gender == ob.gender;
    }
    
    public int compareTo(Person p){
        if(this.name.equals(p.name)){
            return this.age - p.age;
        }
        return this.name.compareTo(p.name);
    }
}

class Student extends Person{
    String stuNo;
    String clazz;

    //建议使用super复用Person类的相关有参构造函数
    public Student(String name, int age, boolean gender, String stuNo, String clazz){
        super(name,age,gender);
        this.stuNo = stuNo;
        this.clazz = clazz;
    }

    public String toString(){
        return "Student:" + super.toString() + "-" + this.stuNo + "-" + this.clazz;
    }         //返回 “Student:person的toString-stuNo-clazz”格式的字符串

    public boolean equals(Object obj){
        if(super.equals(obj)==true){
            Student ob = (Student)obj;
            if(this.clazz.equals(ob.clazz) && this.stuNo.equals(ob.stuNo)){
                return true;
            }
        }
        return false;
    }//首先调用父类的equals方法,如果返回true,则继续比较stuNo与clazz。

}


class Company{
    String name;
    public Company(String name){
        this.name = name;
    }
    public String toString(){
        return this.name;
    }
    public boolean equals(Object obj){
        Company ob = (Company) obj;
        return this.name.equals(ob.name);
    }//name相同返回true
}

class Employee extends Person{
    public Company company;
    public double salary;
        //建议使用super复用Person类的相关有参构造函数
    public Employee(String name, int age, boolean gender, double salary, Company company){
        super(name,age,gender);
        this.salary = salary;
        this.company = company;
    }

    public String toString(){
        return "Employee:" + super.toString() + "-" + this.company + "-" + this.salary;
    } 
    public boolean equals(Object obj){
        if(super.equals(obj)){
            Employee ob = (Employee)obj;
            String a = new DecimalFormat("#.#").format(this.salary);
            String b = new DecimalFormat("#.#").format(ob.salary);
            return this.company.equals(ob.company) && a.equals(b);
        }
        return false;
    }//首先调用父类的equals方法,如果返回true。再比较company与salary。
    //比较salary属性时,使用DecimalFormat df = new DecimalFormat("#.#");保留1位小数
}

public class Main {

    static Scanner in = new Scanner(System.in);
    public static void main(String[] args) {
        List<Person> ps = new ArrayList<>();
        List<Student> st = new ArrayList<>();
        List<Employee> em = new ArrayList<>();
        while(true){
            String op = in.next();
            if(op.equals("s")){
                String name = in.next();
                int age = in.nextInt();
                boolean gender =  in.nextBoolean();
                String stuNo = in.next();
                String clazz = in.next();
                Student s = new Student(name,age,gender,stuNo,clazz);
                ps.add(s);
                st.add(s);
            }
            else if(op.equals("e")){
                String name = in.next();
                int age = in.nextInt();
                boolean gender =  in.nextBoolean();
                double salary = in.nextDouble();
                String company = in.next();
                Employee e = new Employee(name,age,gender,salary,new Company(company));
                ps.add(e);
                em.add(e);
            }
            else{
                Collections.sort(ps);
                for(int i=0;i<ps.size();i++) {
                    System.out.println(ps.get(i));
                }
                String tempString = in.next();
                if(tempString.compareTo("exit")==0||tempString.compareTo("return")==0) {
                    return;
                }
                List<Student> tst = new ArrayList<>();
                List<Employee> tem = new ArrayList<>();
                System.out.println("stuList");
                for(int i=0;i<st.size();i++) {
                    boolean flag = true;
                    for(int j=0;j<tst.size();j++){
                        if(st.get(i).equals(tst.get(j))){
                            //System.out.println(1);
                            flag = false;
                        }
                    }
                    if(flag){
                        tst.add(st.get(i));
                    }
                }
                Collections.sort(tst);
                for(int i=0;i<tst.size();i++){
                    System.out.println(tst.get(i));
                }
                System.out.println("empList");
                //System.out.println(em.size());
                for(int i=0;i<em.size();i++) {
                    boolean flag = true;
                    for(int j=0;j<tem.size();j++){
                        if(em.get(i).equals(tem.get(j))){
                            flag = false;
                        }
                    }
                    if(flag){
                        tem.add(em.get(i));
                    }
                }
                Collections.sort(tem);
                //System.out.println(tem.size());
                for(int i=0;i<tem.size();i++){
                    System.out.println(tem.get(i));
                }
            }
        }
    }
}

 7-8 定义接口(Biology、Animal)、类(Person)、子类(Pupil)

(1)定义Biology(生物)、Animal(动物)2个接口,其中Biology声明了抽象方法breathe( ),Animal声明了抽象方法eat( )sleep( )
(2)定义一个类Person(人)实现上述2个接口,实现了所有的抽象方法,同时自己还有一个方法think( )。breathe()、eat()、sleep()、think()四个方法分别输出:
我喜欢呼吸新鲜空气
我会按时吃饭
早睡早起身体好
我喜欢思考
(3)定义Person类的子类Pupil(小学生),有私有的成员变量school(学校),公有的成员方法setSchool( )getSchool( )分别用于设置、获取学校信息。
(4)在测试类Main中,用Pupil类创建一个对象zhangsan。尝试从键盘输入学校信息给zhangsan,获取到该信息后输出该学校信息,格式为“我的学校是XXX”;依次调用zhangsan的breathe()、eat()、sleep()、think()方法。

输入格式:

从键盘输入一个学校名称(字符串格式)

输出格式:

第一行输出:我的学校是XXX(XXX为输入的学校名称)
第二行是breathe()方法的输出
第三行是eat()方法的输出
第四行是sleep()方法的输出
第五行是think()方法的输出

输入样例:

在这里给出一组输入。例如:

新余市逸夫小学

输出样例:

在这里给出相应的输出。例如:

我的学校是新余市逸夫小学
我喜欢呼吸新鲜空气
我会按时吃饭
早睡早起身体好
我喜欢思考

 

import java.math.*;
import java.util.*;

interface Biology{
    abstract void breathe();
}

interface Animal{
    abstract void eat();
    abstract void sleep();
}

class Person implements Animal,Biology{
    public void think(){
        System.out.println("我喜欢思考");
    }

    public void eat(){
        System.out.println("我会按时吃饭");
    }

    public void sleep(){
        System.out.println("早睡早起身体好");
    }

    public void breathe(){
        System.out.println("我喜欢呼吸新鲜空气");
    }
}

class Pupil extends Person{
    String school;

    public void setSchool(String _school){
        this.school = _school;
    }

    public String getSchool(){
        return this.school;
    }
}

public class Main {

    static Scanner in = new Scanner(System.in);
    public static void main(String[] args) {
        String sc = in.next();
        System.out.println("我的学校是" + sc); 
        Pupil p = new Pupil();
        p.breathe() ;
        p.eat();
        p.sleep();
        p.think();
    }
}

7-9 Employee类的层级结构

定义四个类,分别为Employee类、SalariedEmployee类、HourlyEmployee类和CommissionEmployee类。其中Employee类是其他三个类的父类。Employee类包含姓名和身份证号。除此之外,SalariedEmployee类还应包含每月工资;HourlyEmployee类还应包含每小时工资数和工作时间数;CommissionEmployee还应包含提成比例和销售总额。其中HourlyEmployee的工资为:每小时工资数×工作时间数,CommissionEmployee的工资为:提成比例×销售总额。每个类都应有合适的构造方法、数据成员的设置和读取方法。编写一个测试程序,创建这些类的对象,并输出与对象相关的信息。注意子类有时需调用父类的构造方法和被覆盖的方法,成员变量定义为private,对有些方法实现重载。测试程序如下所示:

    public static void main(String [] args){
       Scanner in=new Scanner(System.in);
       Employee [] e=new Employee[3];
       e[0]=new SalariedEmployee(in.next(),in.next(),in.nextDouble());
       e[1]=new HourlyEmployee(in.next(),in.next(),in.nextDouble(),in.nextDouble());
       e[2]=new CommissionEmployee(in.next(),in.next(),in.nextDouble(),in.nextDouble());
       for(int i=0;i<e.length;i++)
       {    
           System.out.println(e[i].getSalary());
           System.out.println(e[i]);
       }
}

输入格式:

输入三行。第一行为一个SalariedEmployee对象的姓名,身份证号和每月工资。第二行为一个HourlyEmployee对象的姓名、身份证号、每小时工资数、工作时间。第三行为一个CommissionEmployee对象的姓名、身份证号、提成比例和销售总额。

输出格式:

输出三个对象的工资和对象的其他信息。每一个对象输出两行,第一行为工资,第二行为对象的信息。

输入样例:

Mike 0001 5000
Jack 0002 20 300
Tom 0003 0.2 50000

输出样例:

5000.0
SalariedEmployee[name=Mike,id=0001][monthSalary=5000.0]
6000.0
HourlyEmployee[name=Jack,id=0002][hourSalary=20.0,workhour=300.0]
10000.0
CommissionEmployee[name=Tom,id=0003][commissionRatio=0.2,sale=50000.0]
import java.math.*;
import java.util.*;

class Employee{
    String name;
    String id;

    public Employee(String _name, String _id){
        this.name = _name;
        this.id = _id;
    }

    public String toString(){
        return "[name=" + this.name + ",id=" + this.id + "]";
    }

    public double getSalary(){
        return 0.0;
    }
}

class SalariedEmployee extends Employee{
    double monthSalary;

    public double getSalary(){
        return this.monthSalary;
    }

    public String toString(){
        return "SalariedEmployee" + super.toString() + "[monthSalary=" + this.monthSalary + "]";
    }

    public SalariedEmployee(String _name, String _id, double _monthSalary){
        super(_name,_id);
        this.monthSalary = _monthSalary;
    }
}

class HourlyEmployee extends Employee{
    double hourSalary;
    double workhour;

    public HourlyEmployee(String _name, String _id, double _hourSalary, double _workhour){
        super(_name,_id);
        this.hourSalary = _hourSalary;
        this.workhour = _workhour;
    }

    public double getSalary(){
        return this.hourSalary * this.workhour;
    }

    public String toString(){
        return "HourlyEmployee" + super.toString() + "[hourSalary=" + this.hourSalary + ",workhour=" + this.workhour + "]";
    }
}

class CommissionEmployee extends Employee{
    double commissionRatio;
    double sale;

    public CommissionEmployee(String _name,String _id, double _commissionRatio, double _sale){
        super(_name,_id);
        this.commissionRatio = _commissionRatio;
        this.sale = _sale;
    }

    public double getSalary(){
        return this.sale * this.commissionRatio;
    }

    public String toString(){
        return "CommissionEmployee" + super.toString() + "[commissionRatio=" + this.commissionRatio + ",sale=" + this.sale + "]";
    }
}

public class Main {
    public static void main(String [] args){
        Scanner in = new Scanner(System.in);
        Employee [] e = new Employee[3];
        e[0] = new SalariedEmployee(in.next(),in.next(),in.nextDouble());
        e[1] = new HourlyEmployee(in.next(),in.next(),in.nextDouble(),in.nextDouble());
        e[2] = new CommissionEmployee(in.next(),in.next(),in.nextDouble(),in.nextDouble());
        for(int i=0;i<e.length;i++){    
           System.out.println(e[i].getSalary());
           System.out.println(e[i]);
        }
    }
}

 文章来源地址https://www.toymoban.com/news/detail-743518.html

到了这里,关于Java程序设计2023-第三次上机练习的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Java面向对象程序设计实验报告(实验二 面向对象基础练习)

     ✨ 作者: 命运之光  ✨  专栏:Java面向对象程序设计实验报告 目录 ✨一、需求设计 ✨二、概要设计 ✨三、详细设计 ✨四、调试结果 ✨五、测试结果 ✨附录:源程序代码(带注释) 测试类demo2 Address类 Employee类 实验二 面向对象基础练习 实验环境: Eclipse+JDK 实验目的:

    2024年02月06日
    浏览(59)
  • 2022级吉林大学面向对象第三次上机测试

    运算符重载、动态内存管理 1.已知字符串类MyString的定义为: 全局函数: const MyString operator + (const MyString ,const MyString );//字符串连接 ostream operator(ostream os, const MyString str); //定向输出 请完整实现MyString类和指定的全局函数。(可以使用new,delete运算以及strcpy,strlen,…等库函数

    2024年02月06日
    浏览(40)
  • python程序设计——练习4

    1.单词统计 — part one 【题目描述】 本题目要求编写程序统计一行字符中单词的个数。所谓“单词”是指连续不含空格的字符串,各单词之间用空格分隔,空格数可以是多个。 【输入描述】 输入给出一行字符。 【输出描述】 在一行中输出单词个数。 【输入样例1】 Let’s g

    2024年02月09日
    浏览(30)
  • 毕业设计商城小程序练习

    文章目录: 前言: 一:参考地址 二:其他 三:优势 四:技术工具 五:基本项目目录 六:主要页面 七:各个功能实现思路 八:补充 相关公主号:公众平台安全助手、微信公众平台、小程序商家助手 相关    web:微信公众平台、微信官方文档 前言: 代码下载:https://gi

    2024年02月16日
    浏览(29)
  • 团体程序设计天梯赛----pta 练习集

    这道超级简单的题目没有任何输入。 你只需要在一行中输出著名短句“Hello World!”就可以了。 解法 略 本题要求你写个程序把给定的符号打印成沙漏的形状。例如给定17个“*”,要求按下列格式打印 解法 记录一下个数就好 给定一个 k 位整数 N,请编写程序统计每种不同的个

    2024年02月13日
    浏览(30)
  • 5、MATLAB程序设计与应用刘卫国(第三版)课后实验五:循环结构程序设计

    目录 一、  二、  三、  四、  五、 已知 求 y的近似值。当n分别取100、1 000、10 000时,结果是多少? 要求 :分别用循环结构和向量运算(使用sum 函数)来实现。 --------------------------------------- 示例代码 --------------------------------------------- --------------------------------------- 运行结果

    2023年04月26日
    浏览(39)
  • 3、MATLAB程序设计与应用刘卫国(第三版)课后实验三:顺序结构程序设计

    目录 一、  二、  三、  四、  五、  六、 从键盘输入一个4位整数,按如下规则加密后输出。加密规则:每位数字都加上7,然后用和除以10的余数取代该数字;然后将第一位数与第三位数互换,第二位数与第四位数互换。 ------------- -------- ------------ ------ 示例代码 ---------------

    2024年02月03日
    浏览(31)
  • 4、MATLAB程序设计与应用刘卫国(第三版)课后实验四:选择结构程序设计

    目录  一、  二、  三、  四、  五、 求分段函数的值   用 if语句实现,分别输出X=-5.0,-3.0,1.0,2.0,2.5,3.0,5.0时的y值。 ------------- -------- ------------ ------ 示例代码 - -------------------------- ------------------ ------------- -------- ------------ ------ 运行结果 - -------------------------- --------

    2024年02月05日
    浏览(33)
  • 团体程序设计天梯赛-练习集L2篇⑦

    🚀欢迎来到本文🚀 🍉个人简介:Hello大家好呀,我是陈童学,一个与你一样正在慢慢前行的普通人。 🏀个人主页:@陈童学哦`CSDN 💡所属专栏:PTA 🎁希望各位→点赞👍 + 收藏⭐️ + 留言📝 ​ ⛱️刷题的当下应是享受的!望与诸君共勉!🏄‍♂️ 下面是PTA的OJ平台 PTA的

    2024年02月11日
    浏览(80)
  • 【C++ 程序设计】实战:C++ 实践练习题(1~10)

    目录 01. 二维数组反对角线之和 02. 奇偶性  03. 指针与变量 04. 员工薪资  05. 整型值(%4d 进行格式化) 06. 求三个数中的最大值和最小值 07. 同一字母次数统计 08. 字符串回文判断 09. 闰年判断 10. 交换两个双精度数 【代码详解】 以上代码 计算的是 反对角线(从右上角到左下

    2024年02月14日
    浏览(30)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包