Southwest Petroleum University PTA (final) Java function topic

foreword

This article is a personal java review, and some codes refer to other blogs.

6-1 Design a rectangle class Rectangle

Design a class called Rectangle to represent a rectangle. This class includes:
two double-type data fields named width and height, which represent the width and height of the rectangle respectively. Both width and height default to 1.
A no-argument constructor.
A rectangle constructor that specifies values ​​for width and height.
A method called getArea() returns the area of ​​this rectangle.
A method called getPerimeter() returns the perimeter of this rectangle.

Class name: Rectangle

Sample referee test procedure:

import java.util.Scanner;
/* 你的代码将被嵌入到这里 */

public class Main {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    double w = input.nextDouble();
    double h = input.nextDouble();
    Rectangle myRectangle = new Rectangle(w, h);
    System.out.println(myRectangle.getArea());
    System.out.println(myRectangle.getPerimeter());

    input.close();
  }
}

Input sample:

3.14  2.78

Sample output:

8.7292
11.84

 answer:

class Rectangle{
    private double width;
    private double  height;
    public Rectangle(){
        this.width = 1;
        this.height=1;
    }
    public Rectangle(double width,double height){
        this.width = width;
        this.height= height;
    }
    public double getArea(){
        return width*height;
    } 
    public double getPerimeter(){
        return 2*(width+height);
    }
}

6-2 Write the base class from the derived class (Java)

The referee test program sample shows a piece of Java code that defines the base class People, derived class , and test the two classes. Some of the code is missing, please complete it to ensure the normal operation of the test program.Student

Function interface definition:

提示:
 观察派生类代码和main方法中的测试代码,补全缺失的代码。

Sample referee test procedure:

Note: The data used in the real test program may be different from the sample test program, but only call the relevant methods (functions) according to the format in the sample.

 
class People{
    protected String id;
    protected String name;
    
    /** 你提交的代码将被嵌在这里(替换此行) **/
    
}

class Student extends People{
    protected String sid;
    protected int score;
    public Student() {
        name = "Pintia Student";
    }
    public Student(String id, String name, String sid, int score) {
        super(id, name);
        this.sid = sid;
        this.score = score;
    }
    public void say() {
        System.out.println("I'm a student. My name is " + this.name + ".");
    }

}
public class Main {
    public static void main(String[] args) {
        Student zs = new Student();
        zs.setId("370211X");
        zs.setName("Zhang San");
        zs.say();
        System.out.println(zs.getId() + " , " + zs.getName());
        
        Student ls = new Student("330106","Li Si","20183001007",98);
        ls.say();
        System.out.println(ls.getId() + " : " + ls.getName());
        
        People ww = new Student();
        ww.setName("Wang Wu");
        ww.say();
        
        People zl = new People("370202", "Zhao Liu");
        zl.say();
    }
}

Input sample:

A set of inputs is given here. For example:

(无)

Sample output:

Here: gives the corresponding output. For example:

I'm a student. My name is Zhang San.
370211X , Zhang San
I'm a student. My name is Li Si.
330106 : Li Si
I'm a student. My name is Wang Wu.
I'm a person! My name is Zhao Liu.

answer:

public String getId(){
	    return id;
	}
public String setId(String id){
	    return this.id=id;
	}

	public void setName(String name){
	    this.name=name;
	}

	public String getName(){
	    return name;
	}

	public People(){
		
	}
	public People(String id,String name) {
		this.id=id;
		this.name=name;
	}
	public void say(){
	    System.out.print("I'm a person! My name is " + this.name + ".");
	    }

6-3 Write derived class constructor (Java)

The referee test program sample shows a piece of Java code that defines the base class People, derived class , and test the two classes. Some of the code is missing, please complete it to ensure the normal operation of the test program.Student

Function interface definition:

 

提示: 观察类的定义和main方法中的测试代码,补全缺失的代码。

Sample referee test procedure:

Note: The data used in the real test program may be different from the sample test program, but only call the relevant methods (functions) according to the format in the sample.

裁判测试程序样例中展示的是一段定义基类People、派生类Student以及测试两个类的相关Java代码,其中缺失了部分代码,请补充完整,以保证测试程序正常运行。

函数接口定义:
提示:
观察类的定义和main方法中的测试代码,补全缺失的代码。
裁判测试程序样例:
注意:真正的测试程序中使用的数据可能与样例测试程序中不同,但仅按照样例中的格式调用相关方法(函数)。

class People{
    private String id;
    private String name;
    public People(String id, String name) {
        this.id = id;
        this.name = name;
    }
    public String getId() {
        return id;
    }
    public String getName() {
        return name;
    }
}

class Student extends People{
    private String sid;
    private int score;
    public Student(String id, String name, String sid, int score) {
    
    /** 你提交的代码将被嵌在这里(替换此行) **/
    
    }
    public String toString(){
        return ("(Name:" + this.getName() 
                + "; id:" + this.getId() 
                + "; sid:" + this.sid
                + "; score:" + this.score 
                + ")");
    }

}
public class Main {
    public static void main(String[] args) {
        Student zs = new Student("370202X", "Zhang San", "1052102", 96);
        System.out.println(zs);
        
    }
}
输入样例:
在这里给出一组输入。例如:

(无)
输出样例:
(Name:Zhang San; id:370202X; sid:1052102; score:96)

Input sample:

A set of inputs is given here. For example:

(无)

Sample output:

(Name:Zhang San; id:370202X; sid:1052102; score:96)

 answer:

super(id,name);
this.sid=sid;
this.score=score;

6-4 Rewrite parent class method equals

Override the equals method of the Object class in the class Student. When the student ID (id) of the Student object is the same, it is judged as the same object.

Function interface definition:

在类Student中重写Object类的equals方法。使Student对象学号(id)相同时判定为同一对象。

Sample referee test procedure:

import java.util.Scanner;
class Student {
     int id;
     String name;
     int age;
     public Student(int id,     String name,     int age) {
         this.id = id;
         this.name = name;
         this.age = age;
     }
     
     /* 请在这里填写答案 */
         
}
public class Main {
    public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
        Student s1 = new Student(sc.nextInt(),sc.next(),sc.nextInt());
        Student s2 = new Student(sc.nextInt(),sc.next(),sc.nextInt());
        System.out.println(s1.equals(s2));
        sc.close();
    }
}

Input sample:

1001 Peter 20
1001 Jack 18

Sample output:

true

 answer

public boolean equals(Object o){
    if(this==o){
        return true;
    }if(o instanceof Student){
        Student s=(Student)o;//把传入的对象转换为Student
		return this.id==s.id;//id相同则返回true
	}else {
		return false;
	}
}

 6-5 A circle class Circle is extended from the abstract class shape class

Please extend a circle class Circle from the following abstract class shape class. The radius of this circle class is a private member, and the class should include a constructor for initializing the radius.

public abstract class shape {// abstract class

public abstract double getArea();// 求面积

public abstract double getPerimeter(); // 求周长

}

The main class inputs the radius value of the circle from the keyboard, creates a circle object, and then outputs the area and circumference of the circle. Keep 4 decimal places.

 

圆形类名Circle

Sample referee test procedure:

import java.util.Scanner;
import java.text.DecimalFormat;
 
abstract class shape {// 抽象类
     /* 抽象方法 求面积 */
    public abstract double getArea( );
 
    /* 抽象方法 求周长 */
    public abstract double getPerimeter( );
}

/* 你提交的代码将被嵌入到这里 */

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        DecimalFormat d = new DecimalFormat("#.####");// 保留4位小数
         double r = input.nextDouble( ); 
        shape c = new  Circle(r);
 
        System.out.println(d.format(c.getArea()));
        System.out.println(d.format(c.getPerimeter()));
        input.close();
    } 
}

Input sample:

3.1415926

 

Sample output:

31.0063
19.7392

answer: 

class Circle extends shape{
    private double radius;
    public Circle(double  r){
        radius=r;
    }
    public double getArea(){
        return Math.PI*radius*radius;
    }
    public double getPerimeter(){
        return 2*Math.PI*radius;
    }
}

 

6-6 Create a right triangle class that implements the IShape interface 

Create a right triangle class (regular triangle) RTriangle class, implement the following interface IShape. The length of the two right-angled sides is used as a private member of the RTriangle class, and the class contains a construction method whose parameter is the right-angled side.

interface IShape {// interface

public abstract double getArea(); // abstract method to calculate area

public abstract double getPerimeter(); // abstract method to find perimeter

}

###Definition of right triangle class:

直角三角形类的构造函数原型如下:
RTriangle(double a, double b);

where  a and  b are the two sides of a right triangle.

Sample referee test procedure:


import java.util.Scanner;
import java.text.DecimalFormat;
 
interface IShape {
    public abstract double getArea();
 
    public abstract double getPerimeter();
}
 
/*你写的代码将嵌入到这里*/


public class Main {
    public static void main(String[] args) {
        DecimalFormat d = new DecimalFormat("#.####");
        Scanner input = new Scanner(System.in);
        double a = input.nextDouble();
        double b = input.nextDouble();
        IShape r = new RTriangle(a, b);
        System.out.println(d.format(r.getArea()));
        System.out.println(d.format(r.getPerimeter()));
        input.close();
    }
}

Input sample:

3.1 4.2

 

Sample output:

6.51
12.5202

 

class RTriangle implements IShape{
    private double a,b;
    public RTriangle(double a, double b){
        this.a=a;
        this.b=b;
    }
    public double getArea(){
        return a*b*0.5;
    }
    public double getPerimeter(){
        return a+b+Math.sqrt(a*a+b*b);
    }
}

 

6-7 jmu-Java-06 exception - capture of various types of exceptions

 

If the code in the try block may throw multiple exceptions, and there may be an inheritance relationship between these exceptions, then you need to pay attention to the order of capture when catching exceptions.

Complete the following code to make the program run normally.

Referee Test Procedure:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    while (sc.hasNext()) {
        String choice = sc.next();
        try {
            if (choice.equals("number"))
                throw new NumberFormatException();
            else if (choice.equals("illegal")) {
                throw new IllegalArgumentException();
            } else if (choice.equals("except")) {
                throw new Exception();
            } else
            break;
        }
        /*这里放置你的答案*/
    }//end while
    sc.close();
}

###Output description Two lines of information should be output in the block:
Line 1: Custom information should be output. Line 2 of the output sample is as follows : Use to output exception information, e is the generated exception.catch
number format exception
System.out.println(e)

input sample

number illegal except quit

output sample

number format exception
java.lang.NumberFormatException
illegal argument exception
java.lang.IllegalArgumentException
other exception
java.lang.Exception

 answer

catch(NumberFormatException e){
    System.out.println("number format exception");
     System.out.println(e);
}
catch(IllegalArgumentException e){
     System.out.println("illegal argument exception");
     System.out.println(e);
}
catch(Exception e){
     System.out.println("other exception");
     System.out.println(e);
}

 

6-8 jmu-Java-03 Object-Oriented Basics-Object 

Enter an integer n, create n objects, and put them in the same array.

If input c, then new Computer(); //Note: Computer is an existing class in the system, no need to write it yourself

If entered d, a type object is created from the ensuing input Double.

If entered i, a type object is created from the ensuing input Integer.

If entered s, a type object is created from the ensuing input String.

If it is not the above input, the object will not be created, but will be nullstored in the corresponding position of the array.

Finally, all objects in the array are output in reverse ordernull , and if the element at the corresponding position in the array is , it is not output.

Referee Test Procedure:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    //这边是你的代码
    sc.close();
}

Input sample:

5
c
d 2.3
other
i 10
s Test

Sample output:

Test
10
2.3
//这行显示Computer对象toString方法

answer 

int n=sc.nextInt();
		Object a[]=new Object[n];
		for(int i=0;i<n;i++) {
			String s=sc.next();
			if(s.equals("c")) {
				a[i]=new Computer();
			}else if(s.equals("d")) {
				a[i]=new Double(sc.nextDouble());
			}else if(s.equals("i")) {
				a[i]=new Integer(sc.nextInt());
			}else if(s.equals("s")) {
				a[i]=new String(sc.next());
			}else {
				a[i]=null;
			}
		}
		for(int i=n-1;i>=0;i--) {
			if(a[i] instanceof String) {
				System.out.println(a[i].toString());
			}else if(a[i] instanceof Integer) {
				System.out.println(a[i].toString());
			}else if(a[i] instanceof Double) {
				System.out.println(a[i].toString());
			}else if(a[i] instanceof Computer) {
				System.out.println(a[i].toString());
			}else {
				
			}
		}

6-9 Demographics 

When this question is running, the keyboard is required to input the information of 10 people (each person's information includes: name, gender, age, ethnicity), and the students are required to implement a function to count the number of people whose ethnicity is "Han".

Function interface definition:

 

public static int numofHan(String data[])

where  data[] is the parameter passed in. data[]Each element in is a complete string of personnel information, which consists of "name, gender, age, nationality", and the items are separated by English half-width commas. The function must return the number of Han people.

Sample referee test procedure:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        final int HUMANNUM=10;
        String persons[]=new String[HUMANNUM];
        Scanner in=new Scanner(System.in);
        for(int i=0;i<persons.length;i++)
            persons[i]=in.nextLine();
        int result=numofHan(persons);
        System.out.println(result);
    
    }
    
    /*在此处给出函数numofHan()*/
    

}

Input sample:

Tom_1,男,19,汉族
Tom_2,女,18,汉族
Tom_3,男,20,满族
Tom_4,男,18,汉族
Tom_5,男,19,汉族人
Tom_6,女,17,汉族
Tom_7,男,19,蒙古族
汉族朋友_1,男,18,汉族
Tom_8,male,19,老外
Tom_9,female,20,汉族

Sample output:

7

answer:

public static int numofHan(String data[]){
int count=0;//定义整形变量
    for(int i=0;i<data.length;i++)//遍历整个字符串数组
    {
        if(data[i].indexOf("汉",4)>0)//indexOf方法可以获取到一个字符串中指定字符的位置,例如从字符串第7个字符开始,查找”汉“,找不到返回-1
            {
                count++;
            }
    }
    return count;
}

6-10 jmu-Java-05 collection-deletion of specified elements in List 

Write the following two functions

//以空格(单个或多个)为分隔符,将line中的元素抽取出来,放入一个List
public static List<String> convertStringToList(String line) 
//在list中移除掉与str内容相同的元素
public static void remove(List<String> list, String str)

Referee Test Procedure:

public class Main {

    /*covnertStringToList函数代码*/   
        
    /*remove函数代码*/
        
     public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNextLine()){
            List<String> list = convertStringToList(sc.nextLine());
            System.out.println(list);
            String word = sc.nextLine();
            remove(list,word);
            System.out.println(list);
        }
        sc.close();
    }

}

 

Example description: 4 sets of test data are shown below.

input sample

1 2 1 2 1 1 1 2
1
11 1 11 1 11
11
2 2 2 
1
1   2 3 4 1 3 1
1

output sample

[1, 2, 1, 2, 1, 1, 1, 2]
[2, 2, 2]
[11, 1, 11, 1, 11]
[1, 1]
[2, 2, 2]
[2, 2, 2]
[1, 2, 3, 4, 1, 3, 1]
[2, 3, 4, 3]

answer 

	public static List<String> convertStringToList(String line) {
		List<String> a=new ArrayList<String>();
		String s[]=line.split("\\s+");
		for(int i=0;i<s.length;i++) {
			a.add(s[i]);
		}
		return a;
	}
	public static void remove(List<String> list, String str) {
		for(int i=0;i<list.size();) {
			if(list.get(i).equals(str)) {
				list.remove(i);
				i=0;
			}else {
				i++;
			}
		}
	}

 

6-11 jmu-Java-07 Multithreading-Thread

Write a MyThread class that inherits from Thread. The number of cycles n can be specified when creating an object of the MyThread class.
Function: Output integers from 0 to n-1. and at the end System.out.println(Thread.currentThread().getName()+" "+isAlive())print the identity information using

Referee Test Procedure:

import java.util.Scanner;

/*这里放置你的答案,即MyThread类的代码*/

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Thread t1 = new MyThread(Integer.parseInt(sc.next()));
        t1.start();
    }
}

 

Input sample:

3

Sample output:

0
1
2
标识信息

 answer:

class MyThread extends Thread {
    private int n;

    public MyThread(int n) {
        this.n = n;
    }

    public void run() {
        for (int i = 0; i < n; i++) {
            System.out.println(i);
        }
        System.out.println(Thread.currentThread().getName() + " " + isAlive());
    }
}

 6-12 jmu-Java-07 multithreading-PrintTask

Write the PrintTask class to implement Runnablethe interface.
Function: Output an integer from 0 to n-1 (n is specified when creating the PrintTask object). And use System.out.println(Thread.currentThread().getName());the output identification information at the end.

Referee Test Procedure:

import java.util.Scanner;

/*这里放置你的答案,即PrintTask类的代码*/

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        PrintTask task = new PrintTask(Integer.parseInt(sc.next()));
        Thread t1 = new Thread(task);
        t1.start();
        sc.close();
    }
}

Input sample:

3

Sample output:

0
1
2
标识信息

answer 

class PrintTask implements Runnable{
    private int n;
    public PrintTask(int n){
        this.n=n;
    }
    public void run(){
        for(int i=0;i<n;i++){
            System.out.println(i);
        }
        System.out.println(Thread.currentThread().getName());
    }
}

6-13 jmu-Java-03 object-oriented basics - coverage and toString 

There are Personclasses, Companyclasses, Employeeclasses.

Among them, the Employee class inherits from the Person class, and the attributes are:

private Company company;
private double salary;

Now it is required to write the method of the Employee class toString, and the returned string format is: toString-salary of the parent class's toString-company

Function interface definition:

 

public String toString()

Input sample:



Sample output:

Li-35-true-MicroSoft-60000.0

 answer

public String toString(){
    return super.toString()+"-"+company.toString()+"-"+salary;
}

 

6-14 students, college students, graduate students

 

Define the Student class, which has the attributes of student number, name, and gender, provides constructors, and get set functions for corresponding attributes, and provides the function attendClass(String className) to indicate class attendance.
Define that the CollegeStudent class inherits from the Student class, has new attributes majors, provides constructors, and provides get and set functions for
new attributes. The get and set functions of attributes provide the function doResearch() to indicate research (print xx is doing research).

Test the constructed class in the main function

Enter a description:

Student information, student number, name, gender
University information, student number, name, gender, major
Postgraduate information, student number, name, gender, major, tutor

Output description:

Student information
University information
Graduate information

Sample referee test procedure:

import java.util.Scanner;
public class Main{
    public static void main(String[] args) {
         Scanner scan = new Scanner(System.in);      
         int no = scan.nextInt();
         String name = scan.next();      
         String sex = scan.next();      
         Student s = new Student(no, name, sex);
         s.print();

         no = scan.nextInt();
         name = scan.next();      
         sex = scan.next();      
         String major = scan.next();
         CollegeStudent c = new CollegeStudent(no, name, sex, major);
         c.print();

         no = scan.nextInt();
         name = scan.next();      
         sex = scan.next();      
         major = scan.next();
         String supervisor = scan.next();
         GraduateStudent g = new GraduateStudent(no, name, sex, major, supervisor );
         g.print();
         g.doResearch();
         scan.close(); 
    }
}

/* 你的代码被嵌在这里*/

Input sample:

A set of inputs is given here. For example:

1 liu female
2 chen female cs
3 li male sc wang

Sample output:

The corresponding output is given here. For example:

no: 1
name: liu
sex: female
no: 2
name: chen
sex: female
major: cs
no: 3
name: li
sex: male
major: sc
supervisor: wang
li is doing research

answer 

class Student{
    private int id;
    private String name ,sex;
    public Student(int id ,String name,String sex){
        this.id=id;
        this.name=name;
        this.sex=sex;
    }
    public String getName() {
        return this.name;
    }
    public void print(){
        System.out.println("no: "+this.id);
        System.out.println("name: "+this.name);
        System.out.println("sex: "+this.sex);
    }
}
class CollegeStudent extends Student{
    private String major;
    public CollegeStudent(int id,String name ,String sex,String major){
        super(id,name,sex);
        this.major=major;
    }
    public void print(){
        super.print();
        System.out.println("major: "+this.major);
    }
}
class GraduateStudent extends CollegeStudent{
    private String supervisor;
    public GraduateStudent (int id,String name ,String sex,String major,String supervisor){
        super(id,name,sex,major);
        this.supervisor=supervisor;
    }
      public void print(){
        super.print();
        System.out.println("supervisor: "+this.supervisor);
    }
    public void doResearch(){
		System.out.println(this.getName()+" is doing research");
	}
}
 

 

6-15 Shape class

 

Define a shape class Shape, provide functions to calculate the perimeter getPerimeter() and area getArea()
define a subclass square class Square inherits from the Shape class, has a side length attribute, provides a constructor, and can calculate the perimeter getPerimeter() and area getArea()
defines a subclass of the rectangle class Rectangle inherited from the Square class, has length and width properties, provides constructors, can calculate the perimeter getPerimeter() and area getArea() defines a subclass of the circle class Circle inherited from
Shape, has Radius attribute, providing constructor, able to calculate perimeter getPerimeter() and area getArea()

In the main function, construct the objects of the three subclasses respectively, and output their perimeter and area.
Tip: Use System.out.printf("%.2f",d) for formatted output

Enter a description:

The side length of the square class The length and width
of the rectangle class
The radius of the circle class

Output description:

Perimeter and area of ​​a square
Perimeter and area of ​​a rectangle

Sample referee test procedure:

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(); 
    }
}

/* 你的代码被嵌在这里 */

Input sample:

A set of inputs is given here. For example:

1
1 2
2

Sample output:

The corresponding output is given here. For example:

4.00 1.00
6.00 2.00
12.57 12.57
abstract class Shape{
    abstract double getPerimeter();
    abstract double getArea();
}
class Square extends Shape{
    double  length;
    public Square(double  length){
        this.length =length;
        
    }
    public double getPerimeter(){
        return 4*length;
    }
    public double getArea(){
        return length*length;
    }
}
class Rectangle extends Square{
    double width ;
    public Rectangle(double length ,double width){
        super(length);
        this.width=width ;
    }
    public double getPerimeter(){
        return 2*(length+width);
    }
    public double getArea(){
        return length*width;
    }
}
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*r*r;
    }
    
}

 

6-16 Rectangular cuboid

Define a rectangular class Rectangle, which has length and width attributes, provides constructors, and can calculate the perimeter getPerimeter() and area getArea() Define
a subclass of Rectangle, which has length, width, and height attributes, provides constructors, and getPerimeter function calculations The perimeter of all sides, the getArea function calculates the surface area, and the new getVolume function calculates the volume
In the main function, construct objects of the rectangle class and cuboid class respectively, and output their perimeter, area, and volume, with two decimal places

Enter a description:

The length and width of the rectangle class
The length, width and height of the cuboid class

Output description:

Perimeter and area of ​​a rectangle
Perimeter, surface area, volume of a cuboid

Sample referee test procedure:

import java.util.Scanner;
public class Main{
    public static void main(String[] args) {
         Scanner scan = new Scanner(System.in);      
   
         double length = scan.nextDouble();
         double wide = scan.nextDouble();
         Rectangle r = new Rectangle(length,wide);
         System.out.printf("%.2f ",r.getPerimeter());
         System.out.printf("%.2f",r.getArea());
System.out.println();
         length = scan.nextDouble();
         wide = scan.nextDouble();
         double height = scan.nextDouble();
         Cuboid  c = new Cuboid (length, wide, height);
         System.out.printf("%.2f ",c.getPerimeter());
         System.out.printf("%.2f ",c.getArea());
         System.out.printf("%.2f",c.getVolume());

         scan.close(); 
    }
}

/* 你的代码被嵌在这里 */

Input sample:

A set of inputs is given here. For example:

1 2
1 2 3

Sample output:

The corresponding output is given here. For example:

6.00 2.00
24.00 22.00 6.00

 answer:

class Rectangle{
    private double l,w;
    public Rectangle(double l,double w){
        this.l=l;
        this.w=w;
    }
    public double getPerimeter(){
        return 2*(l+w);
    }
    public double getArea(){
        return l*w;
    }
}
class Cuboid {
    private double h,l1,w1;
    
    public Cuboid(double l1,double w1,double h){
        this.l1=l1;
        this.w1=w1;
        this.h=h;
    }
    
    public double getPerimeter(){
        return 4*(l1+w1+h);
    }
    public double getArea(){
        return 2*(l1*w1+w1*h+h*l1);
    }
    public double getVolume(){
        return l1*w1*h;
    }
}

 

6-17 Cylinder calculation

 

Unit Zhejiang Gongshang University Hangzhou Business School

1. Construct a Circle class:

1) This class has a double member variable radius to store the radius;

2) This class has a parameterized construction method, which assigns a value to the member variable radius;

3) This class has two methods getArea and getLength, which can calculate high-precision area and perimeter using radius and Math.PI.

2. Construct a Column class:

1) This class has a Circle member variable bottom which is the bottom surface of the cylinder;

2) This class has a double member variable height to store the height of the cylinder;

3) This class has getBottom and setBottom methods as the access method and assignment method of the member variable bottom;

4) This class has getHeight and setHeight methods as the access method and assignment method of the member variable height;

5) This class has a getVolume method, which calculates and returns the volume of the cylinder.

Sample referee test procedure:

在这里给出函数被调用进行测试的例子。例如:
import java.util.Scanner;
public class Main {
     public static void main(String[] args) {
       Scanner scanner=new Scanner(System.in);      
       double r=scanner.nextDouble();
       double h=scanner.nextDouble();
       Circle c = new Circle(r);
       Column column=new Column();
       column.setBottom(c);
       column.setHeight(h);
       System.out.printf("底面面积和周长分别为:%.2f %.2f\n",column.getBottom().getArea(),column.getBottom().getLength());
       System.out.printf("体积为:%.2f\n",column.getVolume());      
       scanner.close();
   }
}

/* 请在这里填写答案 */

Input sample:

A set of inputs is given here. For example:

10 2

Sample output:

The corresponding output is given here. For example:

底面面积和周长分别为:314.16 62.83
体积为:628.32

 answer:

class Circle{
    private double radius;
    public  Circle(double r){
        this.radius=r;
    }
    public double getArea(){
        return Math.PI*radius*radius;
    }
    public double getLength(){
        return 2.0*Math.PI*radius;
    }
}
class Column {
    private Circle bottom;
    private double height;
    
    public void setBottom(Circle bottom){
        this.bottom=bottom;
    }
    public void setHeight(double height){
        this.height=height;
    }
    public double getHeight() {
        return height;
    }
    public Circle getBottom() {
        return bottom;
    }
    
    public double getVolume(){
        return bottom.getArea()*height;
    }
    
}

6-18 Book class design

Book class design

Create a book class: Book class:
(1) private members of string name and  int price
(2) Contains parameterized construction methods and no-argument construction methods
(3) member method public void printInfo()

The referee test program sample shows the relevant Java code of the test class. Some codes are missing, please complete them to ensure the normal operation of the test program.

Sample referee test procedure:

import java.util.Scanner;

/* 请在这里补充代码 */



public class Main {
    
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        
        String name = in.next();
        int price = in.nextInt();
        Book book1 = new Book(name,price);
        
        Book book2 = new Book();
        
        book1.printInfo();
        book2.printInfo();
        
        in.close();

    }

}

 

Input sample:

C语言程序设计 46

Sample output:

The corresponding output is given here. For example:

C语言程序设计-46
Java程序设计-54

answer: 

class Book{
    private String name ;
    private int price;
    public Book(){
        this.name ="Java程序设计";
        this.price=54;
    }
    public Book(String name,int price){
        this.name=name;
        this.price =price ;
        
    }
    
    public void printInfo(){
        System.out.println(this.name+'-'+this.price);
    }
}

 

6-19 Flower class design

Flower class design
Create a flower class: Flower class:
(1) private members of string name, String color, double price
(2) Contains parameterized construction method and no parameter construction method
(3) member method public void printInfo()

The referee test program sample shows the relevant Java code of the test class. Some codes are missing, please complete them to ensure the normal operation of the test program.

Sample referee test procedure:

 


import java.util.Scanner;

/* 请在这里补充代码 */



public class Main {
    
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        
        String name = in.next();
        String color = in.next();
        double price = in.nextDouble();
        Flower flower1 = new Flower(name,color,price);
        
        Flower flower2 = new Flower();
        
        flower1.printInfo();
        flower2.printInfo();
        
        in.close();

    }

}


输入样例:
百合花 白色 108.8

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

百合花-白色-108.8
玫瑰花-红色-99.9

Input sample:

百合花 白色 108.8

Sample output:

The corresponding output is given here. For example:

百合花-白色-108.8
玫瑰花-红色-99.9

answer:

class Flower{
    private String name;
    private String color;
    private double price;
    public Flower(){
        this.name="玫瑰花";
        this.color="红色";
        this.price=99.9;
    }
    public Flower(String name,String color,double price){
        this.name=name;
        this.color=color;
        this.price=price;
    }
    public void printInfo(){
        System.out.println(this.name+'-'+this.color+'-'+this.price);
    }
}

 

6-20 Person class

Construct the Person class. Including name (name), gender (sex) and age (age). Provide the set and get functions of all attributes, and provide the print function to print its information

Enter a description:

Name (name), gender (sex) and age (age)

Output description:

User Info

Sample referee test procedure:

import java.util.Scanner;
public class Main{
    public static void main(String[] args) {
         Scanner scan = new Scanner(System.in);      
         String name = scan.next();      
         String sex = scan.next();      
         int age = scan.nextInt();
         Person p = new Person();
         p.setName(name);
         p.setSex(sex);
         p.setAge(age);
         p.print();
         scan.close(); 
    }
}

/* 你的代码被嵌在这里 */

Input sample:

A set of inputs is given here. For example:

Lucy male 23

Sample output:

The corresponding output is given here. For example:

name:Lucy; sex:male; age:23

answer 

class Person{
    private String name;
    private String sex;
    private int age;
    public void setName(String name){
        this.name=name;
    }
    public void setSex(String sex){
        this.sex=sex;
    }
    public void setAge(int age){
        this.age=age;
    }
    public String getName(){
        return name;
    }
    public String getSex(){
        return sex;
    }
    public int getAge(){
        return age;
    }
    public void print(){
        System.out.println("name:"+this.name+"; sex:"+this.sex+"; age:"+this.age);
    }
}

6-21 Design a cuboid Cuboid

 

Requirements: Design a class named Cuboid to represent a cuboid. This class includes three double-type data fields named length, width and height, which represent the length, width and height of the cuboid respectively.
A no-argument construction method, the default values ​​of length, width, and height are all 1. A constructor that specifies values ​​for length, width, and height.
A method called getArea() returns the surface area of ​​the cuboid. A method called getVolume() returns the volume of the cuboid.

Function interface definition:

 

public double getArea(); public double getVolume();

Sample referee test procedure:

 
import java.util.Scanner;
/* 你的代码将被嵌入到这里 */

public class Main {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    
    double l = input.nextDouble();
    double w = input.nextDouble();
    double h = input.nextDouble();
    Cuboid myCuboid = new Cuboid(l, w, h);
    System.out.println(myCuboid.getArea());
    System.out.println(myCuboid.getVolume());

    input.close();
  }
}

Input sample:

3.5 2 5

Sample output:

69.0
35.0

 answer

class Cuboid{
    private double l , w ,h;
    public Cuboid(){
        this.l=1;
        this.w=1;
        this.h=1;
    }
      public Cuboid(double l,double w,double h){
        this.l=l;
        this.w=w;
        this.h=h;
    }
    public double getArea(){
        return 2*(l*w+w*h+h*l);
    }
    public double getVolume(){
        return l*w*h;
    }
}

6-22 rectangle

Design a class Rectangle that represents a rectangle. This class uses an object of class Point that represents a coordinate point to express its upper left corner coordinates, and an object of class Dimension that represents a size to represent its size.
Your program must be implemented strictly in accordance with the given class and function declarations.

Function interface definition:

/**
 * Represents a point in 2D, with x and y, like (x,y).
 */
class Point {
    private int x;
    private int y;
    
    /**
     * Creates a point with coordinate at (x,y)
     * @param x the x coordinate
     * @param y the y coordinate
     */
    public Point(int x, int y) {
        
    }
    
    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     * The generated string as: "(x,y)
     */
    @Override
    public String toString() {
        
    }
    
    /**
     * Moves the point with dx and dy.
     * @param dx the distance to be moved at x-axis
     * @param dy the distance to be moved at y-axis
     */
    public void move(int dx, int dy) {
        
    }
    
    /**
     * Calculate the distance between this and p.
     * @param p the other point.
     * @return the distance between this and p.
     */
    public double distance(Point p) {
        
    }
}

/**
 * A dimension in 2D, with width and height.
 */
class Dimension {
    private int width;
    private int height;
    
    /**
     * Creates a dimension with specified width and height.
     * @param width the width of the dimension
     * @param height the height of the dimension
     */
    public Dimension(int width, int height) {
        
    }
    
    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     * The generated string as: "width by height"
     */
    @Override
    public String toString() {
        
    }
    
    /**
     * Resizes the dimension with scales at width and height.
     * Although the scales are in double, the result should be integers as well.
     * @param widthScale the scale at width
     * @param heightScale the scale at height
     */
    public void resize(double widthScale, double heightScale) {
        
    }
    
    /**
     * Calculate the area of this dimension.
     * @return the area of this dimension.
     */
    public int area() {
        
    }
}

/**
 * Represents a rectangle, with a point at its top-left and a dimension.
 *
 */
class Rectangle {
    private Point topleft;
    private Dimension size;
    
    /**
     * Creates a rectangle.
     * @param topleft the coordinate of its top-left 
     * @param size the dimension of its size
     */
    public Rectangle(Point topleft, Dimension size) {
        
    }
    
    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     * The generated string as: "Rectangle at (x,y):width by height"
     */
    public String toString() {
        
    }
    
    /**
     * Moves the rectangle some distance.
     * @param dx the distance to be moved at x-axis
     * @param dy the distance to be moved at y-axis
     */
    public void move(int dx, int dy) {
        
    }
    
    /**
     * Resizes the rectangle at both width and height
     * @param widthScale the scale at width
     * @param heightScale the scale at height
     */
    public void resize(double widthScale, double heightScale) {
        
    }
    
    /**
     * Calculates the area of this rectangle.
     * @return the area of this rectangle.
     */
    public double area() {
        
    }
    
    /**
     * Calculates the distance between this rectangle and r.
     * @param r the other rectangle
     * @return the distance between this rectangle and r.
     */
    public double distance(Rectangle r) {
        
    }
}

 

Sample referee test procedure:

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int x = in.nextInt();
        int y = in.nextInt();
        int width = in.nextInt();
        int height = in.nextInt();
        Rectangle r = new Rectangle(
            new Point(x,y), new Dimension(width, height));
        Rectangle r2 = new Rectangle(
            new Point(x,y), new Dimension(width, height));
        int dx = in.nextInt();
        int dy = in.nextInt();
        r.move(dx, dy);
        double widthScale = in.nextDouble();
        double heightScale = in.nextDouble();
        r.resize(widthScale, heightScale);
        System.out.println(r);
        System.out.printf("%.2f\n", r.area());
        System.out.printf("%.2f\n", r.distance(r2));
        in.close();
    }
}

/* 请在这里填写答案 */

 

Input sample:

0 0 100 100 20 20 2 2

 answer

/**
 * Represents a point in 2D, with x and y, like (x,y).
 */
class Point {
    private int x;
    private int y;
    
    /**
     * Creates a point with coordinate at (x,y)
     * @param x the x coordinate
     * @param y the y coordinate
     */
    public Point(int x, int y) {
        this.x=x;
        this.y=y;
    }
    
    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     * The generated string as: "(x,y)
     */
    @Override
    public String toString() {
        String point=String.format("Rectangle at (%d,%d):",x,y);
    	return point;
    }
    
    /**
     * Moves the point with dx and dy.
     * @param dx the distance to be moved at x-axis
     * @param dy the distance to be moved at y-axis
     */
    public void move(int dx, int dy) {
        x=dx+x;
        y=dy+y;
    }
    
    /**
     * Calculate the distance between this and p.
     * @param p the other point.
     * @return the distance between this and p.
     */
    public double distance(Point p) {
        double number;
        number=Math.sqrt((x-p.x)*(x-p.x)+(y-p.y)*(y-p.y));
    	return number;
    }
}

/**
 * A dimension in 2D, with width and height.
 */
class Dimension {
    private int width;
    private int height;
    
    /**
     * Creates a dimension with specified width and height.
     * @param width the width of the dimension
     * @param height the height of the dimension
     */
    public Dimension(int width, int height) {
        this.width=width;
        this.height=height;
    }
    
    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     * The generated string as: "width by height"
     */
    @Override
    public String toString() {
        String dimention=String.format("%d by %d",width,height);
    	return dimention;
    }
    
    /**
     * Resizes the dimension with scales at width and height.
     * Although the scales are in double, the result should be integers as well.
     * @param widthScale the scale at width
     * @param heightScale the scale at height
     */
    public void resize(double widthScale, double heightScale) {
        width=(int)(width*widthScale);
        height=(int)(height*heightScale);
    }
    
    /**
     * Calculate the area of this dimension.
     * @return the area of this dimension.
     */
    public int area() {
        int a;
        a=width*height;
        return a;
    }
}

/**
 * Represents a rectangle, with a point at its top-left and a dimension.
 *
 */
class Rectangle {
    private Point topleft;
    private Dimension size;
    
    /**
     * Creates a rectangle.
     * @param topleft the coordinate of its top-left 
     * @param size the dimension of its size
     */
    public Rectangle(Point topleft, Dimension size) {
        this.topleft=topleft;
        this.size=size;
        
    }
    
    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     * The generated string as: "Rectangle at (x,y):width by height"
     */
    public String toString() {
        return topleft.toString()+size.toString();
    }
    
    /**
     * Moves the rectangle some distance.
     * @param dx the distance to be moved at x-axis
     * @param dy the distance to be moved at y-axis
     */
    public void move(int dx, int dy) {
        topleft.move(dx,dy);
    }
    
    /**
     * Resizes the rectangle at both width and height
     * @param widthScale the scale at width
     * @param heightScale the scale at height
     */
    public void resize(double widthScale, double heightScale) {
        size.resize(widthScale, heightScale);
    }
    
    /**
     * Calculates the area of this rectangle.
     * @return the area of this rectangle.
     */
    public double area() {
        double number;
        number=size.area();
        return number;
    }
    
    /**
     * Calculates the distance between this rectangle and r.
     * @param r the other rectangle
     * @return the distance between this rectangle and r.
     */
    public double distance(Rectangle r) {
         return topleft.distance(r.topleft);
    }
}

 

6-23 Design rectangle class Rectangle

Design a class called Rectangle to represent a rectangle. This class includes: Two int data fields named width and height, which represent the width and height of the rectangle respectively. The default values ​​of width and height are both 10. A no-argument constructor. A rectangle constructor that specifies values ​​for width and height. A method called getArea() returns the area of ​​this rectangle. A method called getPerimeter() returns the perimeter of this rectangle. .

Sample referee test procedure:

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    int w = input.nextInt();
    int h = input.nextInt();
        
    Rectangle myRectangle1 = new Rectangle(w, h);
    System.out.println(myRectangle1.getArea());
    System.out.println(myRectangle1.getPerimeter());
    
    Rectangle myRectangle2 = new Rectangle();
    System.out.println(myRectangle2.getArea());
    System.out.println(myRectangle2.getPerimeter());
    input.close();
  }
}

/* 请在这里填写答案 */

 

Input sample:

A set of inputs is given here. For example:

3 5

Sample output:

The corresponding output is given here. For example:

15
16
100
40

answer 

class Rectangle{
    private int width;
    private int height;
    public Rectangle(){
        this.width=10;
        this.height=10;
    }
    public Rectangle(int width,int height){
        this.width=width;
        this.height=height;
    }
    public int getArea(){
        return width*height;
    }
    public int getPerimeter(){
        return 2*(width+height);
    }
    
    
}

 

6-24 Animal interface

It is known that there are the following Animal abstract classes and IAbility interfaces. Please write the Animal subclasses Dog and Cat to implement the IAbility interfaces respectively. In addition, write a simulator class Simulator to call the IAbility interface methods. The specific requirements are as follows.

The existing Animal abstract class definition:

abstract class Animal{
    private String name;  //名字
    private int age;   //年龄
    
    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }    
}

 

Existing IAbility interface definitions:

 
interface IAbility{
    void showInfo();  //输出动物信息
    void cry();    //动物发出叫声
}

Requires a Dog subclass you write:

Implement the IAbility interface

The showInfo method outputs the name and age of the Dog. The output format example is: I am a dog, my name is Mike, and I am 2 years old this year (Note: there are no spaces in the output results, and commas are English punctuation marks)

The cry method outputs the sound of the Dog, and the output format example is: Wangwang

Requires a Cat subclass you write:

Implement the IAbility interface

The showInfo method outputs the name and age of the Cat. The output format example is: I am a cat, my name is Anna, and I am 4 years old this year (Note: there are no spaces in the output results, and commas are English punctuation marks)

The cry method outputs the cry of Cat, the output format example is: Meow Meow

The simulator class Simulator that you need to write:

void playSound(IAbility animal): Call the showInfo and cry methods of the class that implements the IAbility interface, and display the name and age of the incoming animal

The existing Main class definition:

public class Main {

    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        IAbility animal=null;
        int type=input.nextInt();
        String name=input.next();
        int age=input.nextInt();
        if (type==1)
            animal=new Dog(name,age);
        else
            animal=new Cat(name,age);
        
        Simulator sim=new Simulator();
        sim.playSound(animal);
        input.close();
    }
}

/***请在这里填写你编写的Dog类、Cat类和Simulator类** */

 

Input sample:

(The scoring points for this question have nothing to do with the input samples)

The first integer represents the animal type, 1 for dogs, 2 for cats

1 Mike 2

Sample output:

我是一只狗,我的名字是Mike,今年2岁
旺旺
Mike
2

 answer:

class Dog extends Animal implements IAbility {
    public Dog(String name,int age){
         super(name,age);
    }
    public void showInfo() {
        System.out.println("我是一只狗,我的名字是" + getName() + ",今年" + getAge() + "岁");
    }
    public void cry() {
        System.out.println("旺旺");
        System.out.println(getName());
        System.out.println(getAge());
    }
}
class Cat extends Animal implements IAbility{
    public Cat(String name,int age){
        super(name,age);
    }
    public void showInfo() {
        System.out.println("我是一只猫,我的名字是" + getName() + ",今年" + getAge() + "岁");
    }
    public void cry() {
        System.out.println("喵喵");
        System.out.println(getName());
        System.out.println(getAge());
    }
}
class Simulator {
    public void playSound(IAbility animal) {
        animal.showInfo();
        animal.cry();
    }
}

6-25 Designing the Student class

 

Define a Student class to represent student information. The Student class has three private data fields: student number (id, integer), name (name, string), gender (sex, character type, m means male, f means female) three private data fields; there are parameter construction methods to set student number, name , Gender is set as a given parameter; the member method display displays student information.
Note that the definition of the Student class should start like this:
class Student { that is, there should be no public in front of the class of the Student class.

enter

Enter student number, name, gender.

output

Output student number, name, gender.

Sample referee test procedure:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int id = in.nextInt();
        String name = in.next();
        char sex = in.next().charAt(0);
        Student student = new Student(id, name, sex);
        student.display();
        in.close();
    }
}

// 需要同学们完成部分,Student类
class Student {
    // 数据成员
    // 成员方法
}

Input sample:

1000
Tan
m

answer 

class Student{
    private int id;
    private String name;
    private char sex;
    public Student(int id,String name ,char sex){
        this.id=id;
        this.name=name;
        this.sex=sex;
    }
    public void display(){
        System.out.println(this.id);
        System.out.println(this.name);
        System.out.println(this.sex);
    }
}

 

6-26 jmu-Java-07 multithreading - Runnable and anonymous classes

Start a thread in the Main method t1, which outputs 3 lines of information:

  1. main thread name
  2. Thread name of thread t1
  3. All interfaces implemented by thread t1. Hint: use System.out.println(Arrays.toString(getClass().getInterfaces()));output.

Note: This question can also be implemented using Lambda expressions.

Referee Test Procedure:

public class Main {    
    public static void main(String[] args) {
        final String mainThreadName = Thread.currentThread().getName();
        Thread t1 = /*这里放置你的代码*/
        t1.start();
    }
}

Input sample:

 

Sample output:

主线程名
线程t1的线程名
线程t1所实现的所有接口名

 answer

new Thread(() -> {
			System.out.println(mainThreadName);
			System.out.println(Thread.currentThread().getName());
			System.out.println(Arrays.toString(Thread.class.getInterfaces()));
		});


6-27 ICompute interface

Implementation of the ICompute interface

The interface is defined as follows:

interface ICompute{
    // 计算方法
    int compute(int a, int b);
}

where  a and  b are integer parameters.

Improve the following functions:

1. Define four classes: Plus , Subtract , Multiply , and Divide , each of which implements the ICompute interface to complete the addition, subtraction, multiplication, and division of two numbers.
2. Note that when the divisor is 0 in the division operation, -1 is returned

Sample referee test procedure:

import java.util.Scanner;

interface ICompute{
    int compute(int a, int b);
    
}

/* 请在这里补充代码 */

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int a = in.nextInt();
        int b = in.nextInt();
        
        Plus plus = new Plus();
        System.out.println(a + "+" + b + "=" + plus.compute(a, b));
        
        Subtract subtract = new Subtract();
        System.out.println(a + "-" + b + "=" + subtract.compute(a, b));
        
        Multiply multiply = new Multiply();
        System.out.println(a + "*" + b + "=" + multiply.compute(a, b));
        
        Divide divide = new Divide();
        System.out.println(a + "/" + b + "=" + divide.compute(a, b));
        
        
        in.close();

    }

}

Input sample 1:

3 0

Output sample 1:

3+0=3
3-0=3
3*0=0
3/0=-1

Input sample 2:

6 3

Output sample 2:

6+3=9
6-3=3
6*3=18
6/3=2

answer: 

class Plus implements ICompute {
    public int compute(int a, int b) {
        return a + b;
    }
}

class Subtract implements ICompute {
    public int compute(int a, int b) {
        return a - b;
    }
}

class Multiply implements ICompute {
    public int compute(int a, int b) {
        return a * b;
    }
}

class Divide implements ICompute {
    public int compute(int a, int b) {
        if (b == 0) {
            return -1;
        } else {
            return a / b;
        }
    }
}

 6-28 Area interface and Perimeter interface

Realization of Area interface and Perimeter interface

The interface is defined as follows:

// 面积接口
interface Area {
    double PI = 3.14;

    double calArea();
}

// 周长接口
interface Perimeter {
    double calPerimeter();
}

Improve the following functions:

1. Define the Circle class to implement the above two interfaces, including radius member variables and construction methods, where the member variables are private type double radius.
2. Define the Rectangle class to implement the above two interfaces, including length and width member variables and construction methods, where the member variables are private types double length and double width.

Sample referee test procedure:

import java.util.Scanner;

interface Area {
    double PI = 3.14;

    double calArea();
}

interface Perimeter {
    double calPerimeter();
}


/* 请在这里补充代码 */

public class Main {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        double radius = in.nextDouble();
        Circle c1 = new Circle(radius);
        
        double length = in.nextDouble();
        double width = in.nextDouble();
        Rectangle r1 = new Rectangle(length, width);

        System.out.println("c1's perimeter " + c1.calPerimeter());
        System.out.println("c1's rea " + c1.calArea());
        
        System.out.println("r1's perimeter " + r1.calPerimeter());
        System.out.println("r1's rea " + r1.calArea());

        in.close();
    }

}

 

Input sample 1:

4.0
3.0 4.0

Output sample 1:

c1's perimeter 25.12
c1's rea 50.24
r1's perimeter 14.0
r1's rea 12.0

answer:

class Circle implements Area, Perimeter{
    private double radius;
    public Circle(double radius){
        this.radius = radius;
    }
    public double calArea(){
        return PI * radius * radius;
    }
    public double calPerimeter(){
        return 2 * PI * radius;
    }
}

class Rectangle implements Area, Perimeter{
    private double length;
    private double width;
    public Rectangle(double length,double width){
        this.length = length;
        this.width = width;
    }
    public double calArea(){
        return length * width;
    }
    public double calPerimeter(){
        return 2 * (length + width);
    }
}

 

 

Guess you like

Origin blog.csdn.net/LuciaX_/article/details/130648812