# PTA exercise 02 function questions

## 6-1 create a right triangle class to implement IShape interface (10 points)

Create a right triangle RTriangle class to implement the following interface IShape. The length of two right angle edges is the private member of RTriangle class, which contains the construction method with right angle edges as parameters.

interface IShape {/ / interface

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

public abstract double getPerimeter(); / / calculate perimeter with abstract method

}

###Definition of right triangle class:

```The constructor prototype of right triangle class is as follows:
RTriangle(double a, double b);```

among   a   and   b   Are the two right sides of a right triangle.

### Example of referee test procedure:

```import java.util.Scanner;
import java.text.DecimalFormat;

interface IShape {
public abstract double getArea();

public abstract double getPerimeter();
}

/*The code you write will be embedded here*/

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 example:

`3.1 4.2`

No blank lines at the end

### Output example:

```6.51
12.5202```

No blank lines at the end

```class RTriangle implements IShape{
private double a,b;

public RTriangle(double a, double b) {
this.a = a;
this.b = b;
}

public double getArea() {
return 0.5*a*b;
}

public double getPerimeter() {
return a+b+Math.sqrt(a*a+b*b);
}
}```

## 6-2 extend a circular class circle from the abstract class shape class (10 points)

Please extend a circular class Circle from the following abstract class shape class. The radius of this class Circle is a private member, and the class should contain the construction method of initializing the radius.

public abstract class shape {/ / abstract class

```public abstract double getArea();// Find area

public abstract double getPerimeter(); // Find perimeter```

}

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

```Circular class name Circle
```

### Example of referee test procedure:

```import java.util.Scanner;
import java.text.DecimalFormat;

abstract class shape {// abstract class
/* Abstract method for calculating area */
public abstract double getArea( );

/* Abstract method for perimeter */
public abstract double getPerimeter( );
}

/* The code you submit will be embedded here */

public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
DecimalFormat d = new DecimalFormat("#.####"); / / keep 4 decimal places
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 example:

`3.1415926`

No blank lines at the end

### Output example:

```31.0063
19.7392```

No blank lines at the end

```class Circle extends shape
{
final static double PI = 3.1415926535;
}
@Override
public double getArea() {
// TODO Auto-generated method stub
}
@Override
public double getPerimeter() {
// TODO Auto-generated method stub
}
}```

## 6-3 jmu-Java-03 object oriented Basics - coverage and toString (3 points)

There are Person class, Company class and Employee class.

The Employee class inherits from the Person class, and the attributes are:

```private Company company;
private double salary;```

Now you are required to write the toString method of the Employee class. The returned string format is toString company of the parent class toString salary

### Function interface definition:

`public String toString()`

### Output example:

`Li-35-true-MicroSoft-60000.0`
```public String toString() {
return super.toString()+"-"+company.toString()+"-"+salary;
}```

## 6-4 book and audio-visual rental (12 points)

Book and audio-visual stores provide rental services, including the rental of books and DVDs. Books include book titles (String, one word) and prices (double), and DVDs include film titles (String, one word) . they are rented by day, but the rent calculation method is different. The daily rent of books is 1% of the book price, and the daily rent of DVDs is 1 yuan. Construct the inheritance system of books and DVDs, which inherit from the Media class, and provide the method getDailyRent() to return the daily rent, construct the audio-visual store class MediaShop, and provide the static function double calculateRent(Media[] medias, int days) The Media array is constructed in the main function, which contains the objects of books and DVDs. The calculateRent method is called to get and output the rent, with two decimal places reserved

### Enter Description:

Number of books and DVD s to rent

More about books and DVD s

Lease days

Total rent

### Example of referee test procedure:

```import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Media[] ms  = new Media[n];
for (int i=0; i<n; i++) {
String type = sc.next();
if (type.equals("book")) {
ms[i] = new Book(sc.next(), sc.nextDouble());
}else {
ms[i] = new DVD(sc.next());
}
}
double rent = MediaShop.calculateRent(ms, sc.nextInt());
System.out.printf("%.2f", rent);
}
}

### Input example:

```5
book Earth 25.3
book Insights 34
dvd AI
dvd Transformer
book Sun 45.6
20```

No blank lines at the end

### Output example:

`60.98`

No blank lines at the end

```abstract class Media{
abstract double getDailyRent();
}
class MediaShop{
static double calculateRent(Media[] medias, int days) {
double sum=0;
for(Media m:medias)
{
if(m instanceof DVD)
{DVD d=(DVD)m;
sum+=d.getDailyRent()*days;
}else if(m instanceof Book) {
Book b=(Book)m;
sum+=b.getDailyRent()*days;
}
}
return sum;
}}
class Book extends Media{
String name;
double price;
public Book(String name,double price){
this.name=name;
this.price=price;
}
public double getDailyRent() {
return price*0.01;
}
}
class DVD extends Media{
String name;
public DVD(String name){
this.name=name;
}
public double getDailyRent() {
return 1;
}
}```

## 6-5 use inheritance design: teachers. (10 points)

Use inheritance design: teacher class. Make the program run as follows:

```Li 40 Information Technology Institute
Teachers' job is teaching.```

### Function interface definition:

```Define class Teacher, inherit Person
```

### Example of referee test procedure:

```class Person{
String name;
int age;
Person(String name,int age){
this.name = name;
this.age = age;
}
void work(){

}
void show() {
System.out.print(name+" "+age+" ");
}
}

public class Main {

public static void main(String[] args) {

Teacher t = new Teacher("Li",40,"Information Technology Institute");
t.show();
t.work();
}
}```

No input

### Output example:

```Li 40 Information Technology Institute
Teachers' job is teaching.```

No blank lines at the end

```class Teacher extends Person{
String professional;
Teacher(String name, int age, String professional) {
super(name, age);
this.professional=professional;
}
@Override
void work(){
System.out.println(professional);
System.out.println("Teachers' job is teaching.");
}
}```

## 6-6 area summation (5 points)

Due to the different ways of calculating the area of various graphics, in order to make the written program adapt to the area sum of different shapes, when a new graphic is added, it is not necessary to modify other classes, and the interface oriented programming is adopted. The class diagram is shown in the following figure:

According to the above class diagram, you need to design and write the following classes: #######1.IGeometry interface class with double getArea() Interface method 2.Rect class implements the interface with attributes a and B, parameter construction method and implementation of interface method #########3.Circle class implements the interface with attribute r, parameter construction method and implementation of interface method, among which PI=3.14 4.TotalArea class completes the summation of graphic areas of different shapes, with attribute IGeometry[] tuxing array used to store graphic objects of different shapes, and SetTuxing(IGeometry[] t) assign a value to the attribute tuxing. The double computeTotalArea() method is used to calculate the area sum of the graphics stored in the tuxing array and return the area sum.

The main class has been given. Please write the above class in combination with the main class

### Main categories of referee test procedures:

```public class Main {

public static void main(String[] args) {
IGeometry [] tuxing=new IGeometry[29]; //There are 29 Geometry objects
for(int i=0;i<tuxing.length;i++) {   //The 29 Geometry objects are divided into two categories
if(i%2==0)
tuxing[i]=new Rect(16+i,68);
else if(i%2==1)
tuxing[i]=new Circle(10+i);
}
TotalArea computer=new TotalArea();
computer.setTuxing(tuxing);
System.out.printf("Sum of areas of various figures:\n%.2f",computer.computerTotalArea());

}
}

/* Please fill in the answer here. Please complete IGeometry interface class, Rect class, Circle class and TotalArea class in the code box in combination with the main class code*/```

### Input example:

A set of inputs is given here. For example:

`nothing`

No blank lines at the end

### Output example:

The corresponding output is given here. For example:

```Sum of areas of various figures:
58778.36```

No blank lines at the end

```interface IGeometry {
double PI=3.14;
double getArea();
}

class Rect implements IGeometry {

public double a;
public double b;

public Rect(double a,double b) {
this.a=a;
this.b=b;
}

public double getArea() {
// TODO Auto-generated method stub
return a*b;
}

}

class Circle implements IGeometry {

public double r;

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

public double getArea() {
// TODO Auto-generated method stub
return PI*r*r;
}

}

class TotalArea {
IGeometry[] tuxing;

public void setTuxing(IGeometry[] t) {
tuxing=t;
}

public double computerTotalArea() {
double sum=0;

for(int i=0;i<tuxing.length;i++) {
sum+=tuxing[i].getArea();
}

return sum;
}
}```

## 6-7 simulation question: Rewrite parent method equals (5 points)

Override the equals method of the Object class in the Point class. When the x and y coordinates of the Point Object are the same, it is determined to be the same Object.

### Example of referee test procedure:

```import java.util.Scanner;
class Point {
private int xPos, yPos;
public Point(int x, int y) {
xPos = x;
yPos = y;
}
@Override
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Object p1 = new Point(sc.nextInt(),sc.nextInt());
Object p2 = new Point(sc.nextInt(),sc.nextInt());
System.out.println(p1.equals(p2));
sc.close();
}
}```

### Input example:

```10 20
10 20```

No blank lines at the end

### Output example:

`true`

No blank lines at the end

```public boolean equals(Object d){
if(this == d)
return true;
if(d instanceof Point)
{
Point p = (Point ) d;
if(this.xPos == p.xPos && this.yPos == p.yPos)
return true;
}
return false;
}```

## 6-8 general account and checking account (10 points)

Write a Java program, including classes Acount, CheckingAccount and main. Main has been implemented. Please write Acount and CheckingAccount classes.

(1) Write a class Account to represent the general Account object, which contains the following members

① Properties:

1. id: private, int type, indicating the account number;
2. Balance: private, int type, indicating the account balance;

② Method:

1. Account(), construction method, id and balance are initialized to 0;
2. Account(int id, int balance), construction method, set account number and balance with parameters;
3. void setBalance(int balance): modifies the account amount
4. int getBalance(): returns the account amount
5. boolean withdraw(int money): withdraw a specific amount from the account. If the balance is insufficient, return false; otherwise, modify the balance and return true;
6. void deposit(int money): store a specific amount to the account.
7. public String toString(): converts the information of the current account object into a string, for example, the id is 123, the balance is 1000, and returns the string "The balance of account 123 is 1000".

(2) Write a subclass CheckingAccount of the Account class, which represents the checking Account object and contains the following members

① Properties:

1. Overdraft: private, int type, indicating overdraft limit;

② Method:

1. CheckingAccount(), construction method, id, balance and overdraft are initialized to 0;
2. CheckingAccount(int id, int balance, int overdraft), construction method, setting account number, balance and overdraft limit with parameters;
3. boolean withdraw(int money): withdraw a specific amount from the account. If it exceeds the overdraft limit, false is returned; Otherwise, modify the balance and return true;

(3) Write the public class Main to realize the following functions

1. Create a general account a according to the two integer IDs and balance entered by the user;
2. Enter an integer n, indicating that there are n operations on account a;
3. Enter a string and an integer money (representing the operation amount) for each operation
• If the string is "withraw", it indicates the cash withdraw al operation. If the operation is successful, it outputs "withraw" + money + "success". Otherwise, it outputs "withraw" + money + "failed"
• If the string is "deposit", it indicates the deposit operation. After the operation, it outputs "deposit" + money + "success"
1. Use the toString method to output account a information.
2. Create a checking account b according to the three integer IDS, balance and overdraft entered by the user;
3. Enter an integer m, indicating that there are m operations on account b;
4. Enter a string and an integer money (representing the operation amount) for each operation
• If the string is "withraw", it indicates the cash withdraw al operation. If the operation is successful, it outputs "withraw" + money + "success". Otherwise, it outputs "withraw" + money + "failed"
• If the string is "deposit", it indicates the deposit operation. After the operation, it outputs "deposit" + money + "success"
1. Use the toString method to output account b information.

### Example of referee test procedure:

```import java.util.Scanner;

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

Account a = new Account(input.nextInt(),input.nextInt());
n = input.nextInt();
for(int i=0; i < n; i++) {
String op;
int money;
op = input.next();
money = input.nextInt();
if(op.equals("withdraw")) {
if(a.withdraw(money)) {
System.out.println("withdraw " + money + " success");
} else {
System.out.println("withdraw " + money + " failed");
}
} else if(op.equals("deposit")) {
a.deposit(money);
System.out.println("deposit " + money + " success");
}
}
System.out.println(a.toString());

CheckingAccount b = new CheckingAccount(input.nextInt(),input.nextInt(),input.nextInt());
m = input.nextInt();
for(int i=0; i < m; i++) {
String op;
int money;
op = input.next();
money = input.nextInt();
if(op.equals("withdraw")) {
if(b.withdraw(money)) {
System.out.println("withdraw " + money + " success");
} else {
System.out.println("withdraw " + money + " failed");
}
} else if(op.equals("deposit")) {
b.deposit(money);
System.out.println("deposit " + money + " success");
}
}
System.out.println(b.toString());
}
}

### Input example:

```1 100
5
withdraw 200
withdraw 100
deposit 50
deposit 100
withdraw 200
2 100 200
5
withdraw 200
withdraw 100
deposit 50
deposit 100
withdraw 200```

No blank lines at the end

### Output example:

```withdraw 200 failed
withdraw 100 success
deposit 50 success
deposit 100 success
withdraw 200 failed
The balance of account 1 is 150
withdraw 200 success
withdraw 100 success
deposit 50 success
deposit 100 success
withdraw 200 failed
The balance of account 2 is -50```

No blank lines at the end

```class Account{
private int id;
private int balance;
Account(){
id=0;
balance=0;
}
Account(int id,int balance){
this.id=id;
this.balance=balance;
}
void setBalance(int balance) {
this.balance=balance;
}
int getBalance() {
return balance;
}
boolean withdraw(int money) {
if(balance<money) {
return false;
}
else {
balance=balance-money;
return true;
}
}
void deposit(int money) {
this.balance+=money;
}
public String toString() {
return "The balance of account "+id+" is "+this.balance;
}

}
class CheckingAccount extends Account{
private int overdraft;

public CheckingAccount(int a,int b,int c){
super(a,b);
this.overdraft=c;
}

boolean withdraw(int money) {
if(money>(overdraft+this.getBalance())) {
return false;
}
else {
this.setBalance(this.getBalance()-money);
return true;
}
}
}```

Tags: Java Algorithm pta

Posted on Sun, 28 Nov 2021 05:41:17 -0500 by saito