2023面向对象程序设计《实验3》-面向对象

上传练习题答案的初心是监督我自己的Java训练and希望在大家没有思路的时候提供方法让大家获得柳暗花明又一村的感觉,而不是希望大家只一味地摘抄答案做重复而又毫无意义的事情。

“部分代码转自网络”

本篇blog特别鸣谢:

@xihelhy 和我师傅Ahrtolia

T1.

Java每个对象都继承自Object,都有equals、toString等方法。

现在需要定义PersonOverride类并覆盖其toString与equals方法。

1. 新建PersonOverride类

a. 属性:String name、int age、boolean gender,所有的变量必须为私有(private)。

b. 有参构造方法,参数为name, age, gender

c. 无参构造方法,使用this(name, age,gender)调用有参构造方法。参数值分别为"default",1,true

d.toString()方法返回格式为:name-age-gender

e. equals方法需比较name、age、gender,这三者内容都相同,才返回true.

2. main方法

2.1 输入n1,使用无参构造方法创建n1个对象,放入数组persons1。

2.2 输入n2,然后指定name age gender。每创建一个对象都使用equals方法比较该对象是否已经在数组中存在,如果不存在,才将该对象放入数组persons2。

2.3 输出persons1数组中的所有对象

2.4 输出persons2数组中的所有对象

2.5 输出persons2中实际包含的对象的数量

2.5 使用System.out.println(Arrays.toString(PersonOverride.class.getConstructors()));输出PersonOverride的所有构造方法。

提示:使用ArrayList代替数组大幅复简化代码,请尝试重构你的代码。

输入样例:

1
3
zhang 10 true
zhang 10 true
zhang 10 false

输出样例:

default-1-true
zhang-10-true
zhang-10-false
2
[public PersonOverride(), public PersonOverride(java.lang.String,int,boolean)]
import java.util.Arrays;
import java.util.Objects;
import java.util.Scanner;

class PersonOverride {
    String name;
    int age;
    boolean gender;
    public String toString(){
        return name+"-"+age+"-"+gender;
    }
    public boolean equals(Object zjx){
    if(this==zjx) return true;
    if(zjx==null) return false;
    if(this.getClass()!=zjx.getClass()) return false;//判断类是否相同
    PersonOverride p = (PersonOverride)zjx;//强行转换类
    boolean b1 = (Objects.equals(this.name, p.name));//equals比较对象
    boolean b2 = (this.age == p.age);
    boolean b3 = (this.gender == p.gender);
    if(b1 && b2 && b3){
        return true;
    }
    return false;
    }
    public PersonOverride(String name1, int age1, boolean gender1){
        name = name1;
        age = age1;
        gender = gender1;
    }
    public PersonOverride(){
        this("default",1,true);
    }
}
public class Main{
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n1 = in.nextInt();
        PersonOverride[] persons1 = new PersonOverride[n1];
        for (int i = 0; i < n1; i++) {
            persons1[i] = new PersonOverride();
        }
        int n2 = in.nextInt();
        in.nextLine();//遇见回车终止输入
        PersonOverride[] persons2 = new PersonOverride[n2];
        for (int i = 0; i < n2; i++) {
            String str = in.nextLine();
            String[] arr = str.split("\\s+");//转义+遇见\s拆分字符串。。就是把str根据空格拆分成位置不同的同一数组
            PersonOverride temp = new PersonOverride(arr[0],Integer.parseInt(arr[1]),Boolean.valueOf(arr[2]));
            boolean flag = true;
            for (int j = 0; j < n2; j++) {
                if(temp.equals(persons2[j])){
                    flag = false;
                }
            }
            if(flag){
                persons2[i] = new PersonOverride(arr[0],Integer.parseInt(arr[1]),Boolean.valueOf(arr[2]));
            }
        }
        for (int i = 0; i < n1; i++) {
            System.out.println(persons1[i]);
        }
        int i,count = 0;
        for (i = 0; i < n2; i++) {
            if(persons2[i] == null){
                continue;
            }
            count++;
            System.out.println(persons2[i]);
        }
        System.out.println(count);
        System.out.println(Arrays.toString(PersonOverride.class.getConstructors()));
    }
}

T2.

编写程序,实现图形类的继承,并定义相应类对象并进行测试。

  1. 类Shape,无属性,有一个返回0.0的求图形面积的公有方法public double getArea();//求图形面积

  1. 类Circle,继承自Shape,有一个私有实型的属性radius(半径),重写父类继承来的求面积方法,求圆的面积

  1. 类Rectangle,继承自Shape,有两个私有实型属性width和length,重写父类继承来的求面积方法,求矩形的面积

  1. 类Ball,继承自Circle,其属性从父类继承,重写父类求面积方法,求球表面积,此外,定义一求球体积的方法public double getVolume();//求球体积

  1. 类Box,继承自Rectangle,除从父类继承的属性外,再定义一个属性height,重写父类继承来的求面积方法,求立方体表面积,此外,定义一求立方体体积的方法public double getVolume();//求立方体体积

  1. 注意:

  • 每个类均有构造方法,且构造方法内必须输出如下内容:Constructing 类名

  • 每个类属性均为私有,且必须有getter和setter方法(可用Eclipse自动生成)

  • 输出的数值均保留两位小数

主方法内,主要实现四个功能(1-4):

从键盘输入1,则定义圆类,从键盘输入圆的半径后,主要输出圆的面积;

从键盘输入2,则定义矩形类,从键盘输入矩形的宽和长后,主要输出矩形的面积;

从键盘输入3,则定义球类,从键盘输入球的半径后,主要输出球的表面积和体积;

从键盘输入4,则定义立方体类,从键盘输入立方体的宽、长和高度后,主要输出立方体的表面积和体积;

假如数据输入非法(包括圆、矩形、球及立方体对象的属性不大于0和输入选择值非1-4),系统输出Wrong Format

输入格式:

共四种合法输入

  • 1 圆半径

  • 2 矩形宽、长

  • 3 球半径

  • 4 立方体宽、长、高

输出格式:

按照以上需求提示依次输出

输入样例1:

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

1 1.0

输出样例1:

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

Constructing Shape
Constructing Circle
Circle's area:3.14

输入样例2:

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

4 3.6 2.1 0.01211

输出样例2:

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

Constructing Shape
Constructing Rectangle
Constructing Box
Box's surface area:15.26
Box's volume:0.09

输入样例3:

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

2 -2.3 5.110

输出样例2:

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

Wrong Format
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        int n=in.nextInt();
        switch(n) {
        case 1:
            double r;
            r=in.nextDouble();
            if(r<0) 
            {
                System.out.println("Wrong Format");
                
            }
            else
            {
                Circle a=new Circle() ;
                a.setRadius(r);
                System.out.printf("Circle's area:%.2f\n",a.getArea());
            }
            break;
        case 2:
            double a,b;
            a=in.nextDouble();
            b=in.nextDouble();
            if(a<=0||b<=0) {
                System.out.println("Wrong Format");
            }
            else 
            {
                Rectangle c=new Rectangle();
                c.setWidth(a);
                c.setLength(b);
                System.out.printf("Rectangle's area:%.2f\n",c.getArea());
            }
            break;
        case 3:
            double ra;
            ra=in.nextDouble();
            if(ra<=0)
            {
                System.out.println("Wrong Format");
            }
            else
            {
                Ball l=new Ball();
                l.setRadius(ra);
                System.out.printf("Ball's surface area:%.2f\n",l.getArea());
                System.out.printf("Ball's volume:%.2f\n",l.getVolume());
            }
            break;
        case 4:
            double e,f,g;
            e=in.nextDouble();
            f=in.nextDouble();
            g=in.nextDouble();
            if(e<=0||f<=0||g<=0) {
                System.out.println("Wrong Format");
            }
            else 
            {
                Box j=new Box();
                j.setWidth(e);
                j.setLength(f);
                j.setHeight(g);
                System.out.printf("Box's surface area:%.2f\n",j.getArea());
                System.out.printf("Box's volume:%.2f\n",j.getVolume());
            }
            break;
        
        default :
            System.out.println("Wrong Format");
            
        }

    }

}
class Shape{
    public Shape() {
        System.out.println("Constructing Shape");
    }
    public double getArea() {
        return 0.0;
    }
}

class Circle extends Shape
{
    private double radius;
    public Circle()
    {
        System.out.println("Constructing Circle");
    }
    
    public double getArea()
    {
        return Math.PI*radius*radius;
    }
    
    public double getRadius() {
        return radius;
    }
    public void setRadius(double radius) {
        this.radius = radius;
    }
    
}

class Rectangle extends Shape{
    public  Rectangle()
    {
        System.out.println("Constructing Rectangle");
    }
    private double width;
    private double length;
    
    public double getArea() {
        return width*length;
    }
    public double getWidth() {
        return width;
    }
    public void setWidth(double width) {
        this.width = width;
    }
    public double getLength() {
        return length;
    }
    public void setLength(double length) {
        this.length = length;
    }
    
}
class Ball extends Circle{//球继承圆
    public  Ball()
    {
        System.out.println("Constructing Ball");
    }
    
    public double getArea() {
        return 4*super.getArea();
    }
    
    public double getVolume() {
        double l=getRadius();//在外面不用定义半径,因为父类有,只需要用
        return Math.PI*l*l*l*4/3.0;
    }
    
    
}
class Box extends Rectangle{
    public  Box()
    {
        System.out.println("Constructing Box");
    }
    private double height;
    public double getVolume() {
        return super.getArea()*height;//父类的面积
    }
    public double getHeight() {
        return height;
    }
    public void setHeight(double height) {
        this.height = height;
    }
    public double getArea() {
        double l=getWidth();
        double j=getLength();
        return (l*j*2+j*height*2+l*height*2);
    }
    
}

//该段代码来自博主@小混混~(因为我不小心把我的代码删除了

T3.

定义一个形状类Shape,提供计算周长getPerimeter()和面积getArea()的函数

定义一个子类正方形类Square继承自Shape类,拥有边长属性,提供构造函数,能够计算周长getPerimeter()和面积getArea()

定义一个子类长方形类Rectangle继承自Square类,拥有长、宽属性,提供构造函数,能够计算周长getPerimeter()和面积getArea()

定义一个子类圆形类Circle继承自Shape,拥有半径属性,提供构造函数,能够计算周长getPerimeter()和面积getArea()

在main函数中,分别构造三个Shape类的变量,分别指向一个Square、Rectangle、Circle对象,并输出他们的周长、面积.

输入格式:

正方形类的边长

长方形类的长宽

圆类的半径

输出格式:

正方形的周长、面积

长方形的周长、面积

圆形的周长、面积

输入样例:

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

1
1 2
2

输出样例:

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

4.00 1.00
6.00 2.00
12.57 12.57
import java.util.Scanner;
public class Main{
    public static void main(String[] args) {
         Scanner scan = new Scanner(System.in);      
         double length = scan.nextDouble();
         Square s = new Square(length);
         System.out.printf("%.2f ",s.getPerimeter());
         System.out.printf("%.2f\n",s.getArea());

         length = scan.nextDouble();
         double wide = scan.nextDouble();
         Rectangle r = new Rectangle(length,wide);
         System.out.printf("%.2f ",r.getPerimeter());
         System.out.printf("%.2f\n",r.getArea());

         double radius = scan.nextDouble();
         Circle c = new Circle(radius);
         System.out.printf("%.2f ",c.getPerimeter());
         System.out.printf("%.2f\n",c.getArea());

         scan.close(); 
    }
}

abstract class Shape{
    abstract double getPerimeter();
    abstract double getArea();
}

class Square extends Shape{
    
    double len;
    public Square(double len) {
        this.len=len;
    }
    
    public double getPerimeter() {
        return 4*this.len;
    }
    
    public double getArea() {
        return this.len*this.len;
    }
}

class Rectangle extends Square{
    double broad;
    public Rectangle(double len,double broad) {
        super(len);
        this.broad=broad;
    }

    public double getPerimeter() {
        return 2*this.len+2*this.broad;
    }

    public double getArea() {
        return this.len*this.broad;
    } 
}

class Circle extends Shape{
    double r;
    
    public Circle(double r) {
        this.r=r;
    }

    public double getPerimeter() {
        return 2*Math.PI*r;
    }

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

T4.

前言

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

本题描述

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() //获得父类型;

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

思考

  1. 你觉得sumAllArea和sumAllPerimeter方法放在哪个类中更合适?

  1. 是否应该声明为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.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        Shape[] shape = new Shape[n];
        for (int i = 0; i < n; i++) {
            String type = in.next();
            if (type.equals("rect")) {
                int width, length;
                width = in.nextInt();
                length = in.nextInt();
                shape[i] = new Rectangle(width, length);
            }
            else if (type.equals("cir")) {
                int radius = in.nextInt();
                shape[i] = new Circle(radius);
            }
        }

        System.out.println(sumAllPerimeter(shape));
        System.out.println(sumAllArea(shape));
        
        String temp = "[";
        for (int i = 0; i < n; i++) {
            temp += shape[i];
            temp += (i < n-1) ? ", " : "]";
        }
        System.out.println(temp);
        
        for (Shape i : shape) {
            System.out.println(i.getClass()+","+i.getClass().getSuperclass());
        }
    }
    
    static double sumAllPerimeter(Shape[] shape) {
        double sum = 0.0;
        for (Shape i : shape) {
            sum += i.sumAllPerimeter();
        }
        return sum;
    }
    
    static double sumAllArea(Shape[] shape) {
        double sum = 0.0;
        for (Shape i : shape) {
            sum += i.sumAllArea();
        }
        return sum;
    }

}

abstract class Shape{
    final static double PI = 3.14;
    public abstract double sumAllPerimeter();
    public abstract double sumAllArea();
}

class Rectangle extends Shape{
    int width, length;
    public Rectangle(int width,int length) {
        this.width = width;
        this.length = length;
    }
    
    public double sumAllPerimeter() {
        return 2.0 *(width+length);
    }
    
    public double sumAllArea() {
        return width*length;
    }
    
    public String toString() {
        return "Rectangle [" + "width=" + width + ", length=" + length + ']';
    }
}

class Circle extends Shape{
    int radius;
    public Circle(int radius) {
        this.radius = radius;
    }
    
    public double sumAllPerimeter() {
        return PI * radius * 2;
    }
    
    public double sumAllArea() {
        return PI * radius * radius;
    }
    
    public String toString() {
        return "Circle [" + "radius=" + radius + ']';
    }
}

T5.

编写一个完整的Java Application 程序。包含类Shape、类Oval、类ShapeTest,具体要求如下:

(1)编写一个抽象类Shape表示形状对象,包含以下成员

①属性:

PI:double型常数,值为3.1415926;

②方法:

  1. double area(), 抽象方法;

  1. double perimeter(),抽象方法;
    (2)编写一个Shape类的子类Oval,表示椭圆对象,包含以下成员
    ①属性:

  1. a:私有,double型,长轴半径;

  1. b:私有,double型,短轴半径;
    ②方法:

  1. Oval(double a,double b), 构造方法,用参数设置椭圆的长轴半径和短轴半径

  1. Oval(),构造方法,将椭圆的长轴半径和短轴半径都初始化为0。

  1. double area(),重写Shape类中的area方法,返回椭圆的面积( )

  1. double perimeter(),重写Shape类中的perimeter方法,返回椭圆的周长( )

  1. public String toString( ),将把当前椭圆对象的转换成字符串形式,例如长轴半径为10.0,短轴半径为5,返回字符串"Oval(a:10.0,b:5.0)"。
    (3)编写公共类Main,实现如下功能

  1. 输入长轴半径和短轴半径,并创建一个椭圆对象;

  1. 分别用area和perimeter方法,求出以上椭圆的面积和宽度并输出,输出过程中要求使用到toString方法,输出格式如下:

输入格式:

输入长轴半径和短轴半径

输出格式:

输出椭圆的面积和周长。

输入样例:

8 6

输出样例:

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

The area of Oval(a:8.0,b:6.0) is 150.79644480000002
The perimeterof Oval(a:8.0,b:6.0) is 44.42882862370954
import java.util.Scanner;
abstract class Shape{
   double PI=3.1415926;
   abstract double area();
   abstract double perimeter();
}
class Oval extends Shape{
     private double a;
     private double b;
    Oval(double a,double b){
        this.a=a;
        this.b=b;
    }
    Oval(){
        a=0;
        b=0;
    }
    double area(){
      return PI*a*b;
    }
    double perimeter(){
       return 2 * PI * Math.sqrt((a * a + b * b) / 2);
    }
    public String toString(){
return "Oval(a:"+a+",b:"+b+")";
    }
}
public class Main{
    public  static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        double a=sc.nextDouble();
        double b=sc.nextDouble(); 
         Shape s=new Oval(a,b);
        System.out.println("The area of "+s.toString()+" is "+s.area());
        System.out.println("The perimeterof "+s.toString()+" is "+s.perimeter());
    }
}

T6.

  • 利用接口做参数,写个计算器,能完成加减乘除运算。

  1. 定义一个接口ICompute含有一个方法int computer(int n, int m)。

  1. 定义Add类实现接口ICompute,实现computer方法,求m,n之和

  1. 定义Sub类实现接口ICompute,实现computer方法,求n-m之差

  1. 定义Main类,在里面输入两个整数a, b,利用Add类和Sub类的computer方法,求第一个数a和第二个数b之和,输出和,第一个数a和第二个数b之差,输出差。

输入格式:

输入在一行中给出2个整数

输出格式:

输出两个数的和、差

输入样例:

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

6 7

输出样例:

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

13
-1
import java.util.Scanner;
interface Computer {
    int computer(int n, int m);
}
class Add  implements Computer{
    public int computer(int n, int m) {
        return n+m;
    }
}
class Sub implements Computer {
    public int computer(int n, int m) {
        return n-m;
    }
}
public class Main{
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int a=in.nextInt();
        int b=in.nextInt();
        Add ad=new Add();
        Sub su=new Sub();
        int c=ad.computer(a,b);
        int d=su.computer(a,b);
        System.out.println(c);
        System.out.println(d);
    }
}

T7.

定义一个USB接口,并通过Mouse和U盘类实现它,具体要求是:

1.接口名字为USB,里面包括两个抽象方法:

void work();描述可以工作

void stop(); 描述停止工作

2.完成类Mouse,实现接口USB,实现两个方法:

work方法输出“我点点点”;

stop方法输出 “我不能点了”;

3.完成类UPan,实现接口USB,实现两个方法:

work方法输出“我存存存”;

stop方法输出 “我走了”;

4测试类Main中,main方法中

定义接口变量usb1 ,存放鼠标对象,然后调用work和stop方法

定义接口数组usbs,包含两个元素,第0个元素存放一个Upan对象,第1个元素存放Mouse对象,循环数组,对每一个元素都调用work和stop方法。

输入格式:

输出格式:

输出方法调用的结果

输入样例:

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

 

输出样例:

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

我点点点
我不能点了
我存存存
我走了
我点点点
我不能点了
public class Main {
    public static void main(String[] args) {
        Mouse usb1=new Mouse();
        usb1.work();
        usb1.stop();
        USB usbs[]=new USB[2];
        usbs[0]=new UPan();
        usbs[0].work();
        usbs[0].stop();
        usbs[1]=new Mouse();
        usbs[1].work();
        usbs[1].stop();
    }

}
interface USB{
    void work();
    void stop();
}
class Mouse implements USB{
    public void work(){//要写public
        System.out.println("我点点点");
    }
    public void stop(){
        System.out.println("我不能点了");
    }
}
class UPan implements USB{
    public void work(){
        System.out.println("我存存存");
    }
    public void stop(){
        System.out.println("我走了");
    }
}

T8.

定义类ArrayUtils,在该类内部创建一个静态嵌套类PairResult,该嵌套类包含:

属性: private double min与private double max,用于存放最小值最大值

方法:toString方法,格式见下面的输出样例。

为ArrayUtils类创建一个静态方法PairResult findMinMax(double[] values),对传递进来的数组找到其中的最大值和最小值并返回PairResult对象。

main方法说明

  1. 输入n,创建大小为n的double型数组

  1. 依次输入n个double型数值放入数组

  1. 调用findMinMax方法得到结果,并输出。

  1. 最后使用System.out.println(ArrayUtils.PairResult.class)打印标识信息

输入样例

5
0 -1 1 1.1 1.1

输出样例

PairResult [min=-1.0, max=1.1]
\\这里打印标识
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        int n=in.nextInt();
        double s[]=new double[n];
        for(int i=0;i<s.length;i++) {
            double m=in.nextDouble();
            s[i]=m;
        }
        ArrayUtils l=new ArrayUtils();
        double max=s[0];
        double min=s[0];
        
        System.out.println(l.findMinMax(s).toString());
        System.out.println(ArrayUtils.PairResult.class);
    }

}
class ArrayUtils{
    
    static PairResult findMinMax(double[] s)
    {
        PairResult b=new PairResult();
        double min=s[0];
        double max=s[0];
        for(int i=0;i<s.length;i++) {
            if(s[i]>max) {
                max=s[i];
            }
            else if(s[i]<min) {
                min=s[i];
            }
        }
        b.setMax(max);
        b.setMin(min);
        return b;
    }

    static class PairResult{
        private double min;
        private double max;
        public String toString() {
            return "PairResult [min=" + min + ", max=" + max + "]";
        }
        public void setMin(double min) {
            this.min = min;
        }
        public void setMax(double max) {
            this.max = max;
        }
    }
}
  • 15
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值