Abnormal PTA exercises and knowledge points on October 11, 2021

6-1 calculation results (15 points)

The way to calculate the score of gymnasts in gymnastics competition is to remove a maximum score and a minimum score and then calculate the average score. When the school inspects the examination of a subject in a class, it calculates the average score of the whole class. Artistic Gymnastics Gymnastics Classes and schools School Classes are implemented ComputerAverage Interface, but the implementation is different.

Interface method definition:

ComputerAverage The interface has the following methods:
public double average(double x[]);

among   x   Is a parameter passed in by the user. The function must return an average value.

Example of referee test procedure:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        double a[] ;
          double b[];
          Scanner sc=new Scanner(System.in);
          String str1=sc.nextLine();
          String[] str_a=str1.split(" ");
          a=new double[str_a.length];
          for(int i=0;i<str_a.length;i++)
              a[i]=Double.parseDouble(str_a[i]);
          String str2=sc.nextLine();
          String[] str_b=str2.split(" ");
          b=new double[str_b.length];
          for(int i=0;i<str_b.length;i++)
              b[i]=Double.parseDouble(str_b[i]);
          CompurerAverage computer;
          computer=new Gymnastics();  
          double result=computer.average(a); //computer calls the average(double x []) method to pass array a to parameter X
          //System.out.printf("%n");
          System.out.printf("The gymnast scored the final score:%5.3f\n",result);
          computer=new School();  
          result=computer.average(b); //computer calls the average(double x []) method to pass array b to parameter X
          System.out.printf("Average grade of class examination:%-5.2f",result);
    }
}
/* Please fill in the answer here */
//Define interface

//Define the interface implemented by the Gymnastics class


//Define the School class implementation interface

Input example:

9.89 9.88 9.99 9.12 9.69 9.76 8.97
89 56 78 90 100 77 56 45 36 79 98

Output example:

The gymnast scored the final score:9.668
 Average grade of class examination:73.09

My answer:  

//Define the School class implementation interface
interface ComputerAverage {
	double average(double x[]);
}
class Gymnastics implements ComputerAverage {

	@Override
	public double average(double[] x) {
		// TODO Auto-generated method stub
		double total = 0;
		double min,max;
		min = x[0];
		max = x[0];
		for(int i = 0;i<x.length;i++) {
			if(x[i] < min) {
				min = x[i];
			}
			if(x[i] > max) {
				max = x[i];
			}
		}
		for(int j = 0;j<x.length;j++) {
			total = total + x[j];
		}
		total = total - min - max;
		return total/(x.length-2);
	}
}
class School implements ComputerAverage {
	@Override
	public double average(double[] x) {
		double total = 0;
		for(int i = 0;i<x.length;i++) {
			total = total + x[i];
		}
		return total/x.length;
	}
}

6-2 truck loading capacity (15 points)

The truck will carry a batch of goods, which consists of three kinds of goods: TV, computer and washing machine. The truck needs to calculate the weight of the whole batch of goods.

A ComputerWeight interface is required, which has a method:

public double computeWeight()

There are three classes that implement the interface: Television, Computer and WashMachine. These three classes give their own weight by implementing the interface. These three classes all have the attribute weight, which is initialized through the construction method. The computeweight () method of the Television class returns the weight value; The computeWeight() method of Computer returns a value twice the weight; The computeWeight() method of WashMachine returns three times the weight value

There is a Truck class that uses an array of ComputeWeight interface type as a member (the Truck class faces the interface), so the elements of the array can store the reference of the Television object, the reference of the Computer object or the WashMachine

Object. The program can output the total weight of the goods loaded by the Truck object.

Interface method definition:

ComputerWeight Interface method:
 public double computeWeight();

This method is implemented differently in different implementation classes. The computeWeight() method of the Television class returns the weight value; The computeWeight() method of Computer returns a value twice the weight; The computeWeight() method of WashMachine returns three times the weight value.

Example of referee test procedure:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
         ComputerWeight[] goods=new ComputerWeight[650]; //650 pieces of goods
         double[] a=new double[3];//Store the initial value of the weight property of television, computer and washmachine objects
         Scanner sc=new Scanner(System.in);
         String str1=sc.nextLine();
         String[] str_a=str1.split(" ");
         for(int i=0;i<3;i++)
             a[i]=Double.parseDouble(str_a[i]);
          for(int i=0;i<goods.length;i++) { //It is simply divided into three categories
               if(i%3==0)
                 goods[i]=new Television(a[0]);
               else if(i%3==1)
                 goods[i]=new Computer(a[1]);
               else if(i%3==2)
                 goods[i]=new WashMachine(a[2]);
         } 
         Truck truck=new Truck(goods);
         System.out.printf("Weight of goods loaded by truck:%-8.5f kg\n",truck.getTotalWeights());
         goods=new ComputerWeight[68]; //68 pieces of goods
         for(int i=0;i<goods.length;i++) { //It is simply divided into two categories
              if(i%2==0)
                goods[i]=new Television(a[0]);
              else 
                goods[i]=new WashMachine(a[2]);
         } 
         truck.setGoods(goods);
         System.out.printf("Weight of goods loaded by truck:%-8.5f kg\n",truck.getTotalWeights());
    }
}
/* Please fill in the answer here */
//The code for defining the interface ComputerWeight is written below

//The ComputerWeight code that defines the implementation interface of class Television is written below


//The code for defining the class Computer implementation interface ComputerWeight is written below



//The ComputerWeight code that defines the implementation interface of the WashMachine class is written below


//Class Truck, the implementation of the relevant member method code is written below

Input example:

3.5 2.67 13.8

Output example:

Weight of goods loaded by truck:10860.68000 kg
 Weight of goods loaded by truck:1526.60000 kg

My answer:  

interface ComputerWeight
{
	double computerWeight();
}

class Truck
{
	ComputerWeight[] goods = new ComputerWeight[650];
	
	Truck(ComputerWeight[] goods) {
		super();
		this.goods = goods;
	}

	public void setGoods(ComputerWeight[] goods) {
		this.goods = goods;
	}
	
	public double getTotalWeights()
	{
		double sum=0;
		for(int i=0;i<goods.length;i++)
		{
			sum += goods[i].computerWeight();
		}
		return sum;
	}
	
}

class Television implements ComputerWeight
{
	double weight;

	Television(double weight) {
		super();
		this.weight = weight;
	}	
	@Override
	public double computerWeight()
	{
		return weight;
	}
}

class Computer implements ComputerWeight
{
	double weight;
	Computer(double weight)
	{
		this.weight=weight;
	}
	@Override
	public double computerWeight()
	{
		return 2*weight;
	}
}


class WashMachine implements ComputerWeight
{
	double weight;
	WashMachine(double weight)
	{
		this.weight=weight;
	}
	@Override
	public double computerWeight()
	{
		return 3*weight;
	}
}

6-3 cone volume calculation (10 points)

Define an interface IgetArea with the method double getArea(); It is used to calculate the shape area and define another interface IgetPerimeter. There is a method double getPerimeter(); Used to calculate the perimeter of a shape. The interface IShape has a constant PI=3.14 and inherits the interfaces IgetArea and IgetPerimeter

Define a right Triangle RTriangle class to implement the interface IShape. Two right angle edges are private members of the Triangle class. The class contains a construction method with two right angle edges as parameters.

Define a circular class Circle to implement the interface IShape. Radius r is a private member of the Circle class, which contains a constructor with parameter r.

Define a Cone class Cone, in which there IS a member IS of IShape type and a member h of Cone height, including a construction method to assign initial values to IS and h, and a public double getVolume() method to calculate the volume of Cone

Interface definition:

interface IgetArea{
    double getArea();
}
interface IgetPerimeter{
    double getPerimeter();
}

Example of referee test procedure:

import java.lang.*;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
         Scanner input = new Scanner(System.in);
            double a = input.nextDouble();
            double b = input.nextDouble();
            double r=input.nextDouble();
            double h=input.nextDouble();
            IShape[] is=new IShape[2];
            is[0]=new RTriangle(a,b);
            is[1]=new Circle(r);
             Cone cn1;
             for(int i=0;i<2;i++) {
                 cn1=new Cone(is[i],h);
                 String vol=String.format("%.2f", cn1.getVolume());
                 String p=String.format("%.2f",is[i].getPerimeter());
                 System.out.println("Volume"+i+"="+vol+" Perimeter="+p);
             }
    }
}
/* Fill in other codes below */

Input example:

3 4 5 6

Output example:

Volume0=12.00 Perimeter=12.00
Volume1=157.00 Perimeter=31.40

My answer:  

interface IgetArea{
    double getArea();
}
interface IgetPerimeter{
    double getPerimeter();
}

interface IShape extends IgetArea,IgetPerimeter{
	double PI = 3.14;
	double getArea();
	double getPerimeter();
}

class RTriangle implements IShape{
	private double a,b;	

	public RTriangle(double a2, double b2) {
		this.a = a2;
		this.b = b2;
		// TODO Auto-generated constructor stub
	}

	@Override
	public double getArea() {
		// TODO Auto-generated method stub
		double area = 0;
		area = a*b*0.5;
		return area;
	}

	@Override
	public double getPerimeter() {
		// TODO Auto-generated method stub
		double Perimeter=0;
		Perimeter = a+b+Math.sqrt(Math.pow(a,2)+Math.pow(b,2));
		return Perimeter;
	}
}

class Circle implements IShape{
	private double r;

	public Circle(double r2) {
		this.r = r2;
		// TODO Auto-generated constructor stub
	}

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

	@Override
	public double getPerimeter() {
		// TODO Auto-generated method stub
		double Perimeter;
		Perimeter = r*2*PI;
		return Perimeter;
	}	
}

class Cone{
	IShape IS;
	double h;
	
	Cone(IShape iS, double h) {
		IS = iS;
		this.h = h;
	}
	
	public double getVolume()
	{
		double v;
		v=IS.getArea()*h/3;
		return v;
	}
}

6-4 shallow copy and deep copy (10 points)

Object copy in Java refers to copying all attributes (member variables) of an object to another object with the same class type. For example, both object a and object B belong to class S and have attributes a and B. Then copy object a and assign value to object B: B.a=A.a; B.b=A.b;

Shallow Copy: ① for a member variable whose data type is the basic data type, the Shallow Copy will directly transfer the value, that is, copy the attribute value to a new object. Because there are two different pieces of data, modifying the member variable value of one object will not affect the data copied by the other object.

② For a member variable whose data type is a reference data type, for example, if the member variable is an array or a class object, the shallow copy will be passed by reference, that is, just copy the reference value (memory address) of the member variable to the new object. Because in fact, the member variable of both objects points to the same instance. In this case, modifying the member variable in one object will affect the member variable value of another object. To solve this problem, deep copy is introduced:

Deep copy   For reference type member variables, such as arrays or class objects, deep copy will create an object space in the target object, and then copy the contents of the entity object of the member variable corresponding to the original object, so they point to different memory spaces. Changing one will not affect the other.

In Java, there is a method called protected Object clone() throws CloneNotSupportedException. This method is a shallow copy. To implement a deep copy of a class, the class needs to implement the clonable interface, and then override the clone method

Override clone method definition:

class Car implements Cloneable{  //Define a Car class to implement the interface clonable
       //Member variable definition
   public Object clone(){  //Override clone method
       Car c = null;
        try {
                c = (Car)super.clone(); //Call the parent class Object to implement shallow copy
               } catch (CloneNotSupportedException e) {
                        e.printStackTrace();
               }
            //Write code to achieve deep copy

      }
    //Write code to implement other member methods
}

Car   Class contains

1. Properties:

private String name;
private CarDriver driver;
private int[] scores;

2. Parameterless constructor

public Car() {
}

3. Membership method:

@Override
public String toString() {
    return "Car [name=" + name + ", driver=" + driver + ", scores=" + Arrays.toString(scores) + "]";
}

4. Other get and set member methods: public String getName(), public CarDriver getDriver(), public int[] getScores(), and

public void setName(String name),public void setDriver(CarDriver dr),public void setScores(int[] s)

and   clone method for deep copy

CarDriver is a defined class, as follows:

class CarDriver {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public CarDriver() {}
    public String toString() {
        return "CarDriver [name=" + name+"]";
    }
}
public class Main {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int i=sc.nextInt();
        switch(i) {
        case 1:     //Deep copy
            CarDriver cd=new CarDriver();
            Car c1=new Car();
            c1.setDriver(cd);
            cd.setName("d1");
            c1.setName("car1");
            int[] s=new int[2];
            c1.setScores(s);
            Car d1=(Car)c1.clone();
            System.out.println("c1:"+(c1==d1)+" driver:"+(c1.getDriver()==d1.getDriver())+" scores:"+(c1.getScores()==d1.getScores()));
            System.out.println(c1.toString()+" "+d1.getName()+" "+d1.getDriver().getName());    
            break;
        case 2: //        
            Car c2=new Car();
            Car d2=(Car)c2.clone();
            System.out.println("c2:"+(c2==d2)+" driver:"+c2.getDriver()+" "+(c2.getDriver()==d2.getDriver())+" scores:"+c2.getScores()+" "+(c2.getScores()==d2.getScores()));
            break;
        case 3:
            CarDriver cd1=new CarDriver();
            Car c3=new Car();
            c3.setDriver(cd1);
            Car d3=(Car)c3.clone();
            System.out.println("c3:"+(c3==d3)+" driver:"+c3.getDriver()+" "+(c3.getDriver()==d3.getDriver())+" scores:"+c3.getScores()+" "+(c3.getScores()==d3.getScores()));
            break;
        case 4:
            //CarDriver cd3=new CarDriver();
            Car c4=new Car();
            //c4.setDriver(cd3);
            int[] s1=new int[2];
            c4.setScores(s1);
            Car d4=(Car)c4.clone();
            System.out.println("c4:"+(c4==d4)+" driver:"+c4.getDriver()+" "+(c4.getDriver()==d4.getDriver())+" scores:"+" "+(c4.getScores()==d4.getScores()));
            break;

        } 
    }
}

//Now you just need to write the complete code of the Car class below

My answer:

class Car implements Cloneable{
    private String name;
    private CarDriver driver;
    private int[] scores;
    public Car() {
}
    public String getName() {
		return name;
	}
	public CarDriver getDriver() {
		return driver;
	}
	public int[] getScores() {
		return scores;
	}
	public void setName(String name){
	       this.name=name;
	   }
	public void setDriver(CarDriver dr){
	       this.driver=dr;
	   }
	public void setScores(int[] s){
	       this.scores=s;
	   }
    @Override
    public String toString() {
    	return "Car [name=" + name + ", driver=" + driver + ", scores=" + Arrays.toString(scores) + "]";
    }
    public Object clone(){
       Car c = null;
       try {
    	   c = (Car)super.clone();
       } catch (CloneNotSupportedException e) {
    	   e.printStackTrace();
       }
	  if(driver!=null) {
        c.driver=new CarDriver();
       if(driver.getName()!=null)
        c.driver.setName(new String(this.driver.getName()));
	  }
      if(name!=null)
        c.name=new String(this.name);  
      if(scores!=null) {
        c.scores=new int[this.scores.length];
       for(int i=0;i<this.scores.length;i++){
           c.scores[i]=this.scores[i];
         }
       }    
       return c;
   } 
}

6-5 common standard exceptions of the system (10 points)

Common exception classes NumberFormatException, IndexOutOfBoundsException, ArithmeticException, etc. This program establishes a Test_Exception class, which has a test method to detect the occurrence of the above exception objects and output the corresponding information. For example, in case of NumberFormatException exception, output "data format exception"; IndexOutOfBoundsException exception occurs, and "out of bounds exception" is output; ArithmeticException exception occurs and "arithmetic operation exception" is output. ### Test_Exception class definition:

class Test_Exception{
    void test() {
        int n = 0,m = 0,t = 1000;
        int[] a=new int[4];
        int[] b=null;
        Scanner sc=new Scanner(System.in);
        String str=sc.nextLine();
        try {
                    m = Integer.parseInt(str);
                    t=t/m;
                    a[m]=m;
                    b[0]=m;
        }
        //The catch section needs to be filled in by yourself
        catch(...){...}
        catch(...){...}
        catch(...){...}
        catch(Exception e) {
          System.out.println("Exception:"+e.getMessage()); 
         }  //Catch subclass Exception first and catch parent class later
}
}

The first three catch es need to be written by you. When a corresponding exception occurs, the corresponding information is output.

Example of referee test procedure:

Here is an example of a function being called for testing. For example:
import java.util.Scanner;

public class Main{

    public static void main(String[] args) {
        Test_Exception te=new Test_Exception();
        te.test();
    }
}
/* Please write the complete test here_ Exception class */

Input example:

0

Output example:

Arithmetic operation exception

answer:  

class Test_Exception
{
    void test() 
    {
        int n = 0,m = 0,t = 1000;
        int[] a=new int[4];
        int[] b=null;
        Scanner sc=new Scanner(System.in);
        String str=sc.nextLine();
        try 
        {
            m = Integer.parseInt(str);
            t=t/m;
            a[m]=m;
            b[0]=m;
        }
        //The catch section needs to be filled in by yourself
        catch(NumberFormatException e){
            System.out.println("Abnormal data format");
        }
		catch(IndexOutOfBoundsException e){
            System.out.println("Out of bounds anomaly");
        }
		catch(ArithmeticException e){
            System.out.println("Arithmetic operation exception");
        }
		catch(Exception e) {
            System.out.println("Exception:"+e.getMessage());
        }  //Catch subclass Exception first and catch parent class later
    }
}

6-6 check whether the goods are defective (10 points)

The factory checks the equipment with defective products and issues a warning if it is found to be defective. Program and simulate the process of finding defective products.

Write a Product class Product, with member variables name and isDefect (defective or not), and get and set methods.

Write a subclass of Exception, DefectException, which has the message attribute. The constructor DefectException() assigns the "defective" to the message member, and the toShow() method outputs the value of message

Write a Machine class. When the method checkProduct(Product product) of this class finds that the parameter product is defective (the isDefect attribute of product is true), it will throw a DefectException object.

In the try part of the try... Catch statement in the main method of the main class, the program asks the instance of the Machine class to call the checkProduct method. If a defective product is found, the defective product will be handled in the catch part of the try... Catch statement.

Class definition of design:

class Product { //Complete preparation
       boolean isDefect;
       String name;
       //Supplementary code


    }
class DefectException extends Exception { //Complete preparation
       String message;
      //Supplementary code


    }
class Machine {
      public void checkProduct(Product product) throws DefectException {
         if(product.isDefect()) {
             DefectException defect=new DefectException();
             //[code 1] / / throw defect
         }
         else {
             System.out.print(product.getName()+"Not defective! ");
         }
      }
    }

Example of referee test procedure:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
         Machine machine = new Machine();
          String name[] ;
          Scanner sc=new Scanner(System.in);
          name=sc.nextLine().split(" ");
          Product [] products = new Product[name.length]; //Check 6 pieces of goods  
          for(int i= 0;i<name.length;i++) {
             products[i] = new Product();
             if(i%2==0) {
                products[i].setIsDefect(false);
                products[i].setName(name[i]);
             }
             else {
               products[i].setIsDefect(true);
               products[i].setName(name[i]);
             } 
          }
          for(int i= 0;i<products.length;i++) {
            try {
                machine.checkProduct(products[i]);
                System.out.println(products[i].getName()+"Check passed");
            }
            catch(DefectException e) {
               e.toShow();//[code 2] / / e call toShow() method
               System.out.println(products[i].getName()+"Forbidden!"); 
            }
          }     
       } 
}


/* Write the complete Product class, DefectException class and Machine class below*/

Input example:

Computer explosive suit sulfuric acid watch sulfur

Output example:

Computers are not defective! Computer check passed
 Defective products! Explosives are prohibited!
The suit is not defective! Suit check passed
 Defective products! Sulfuric acid is prohibited!
The watch is not defective! The watch passed the inspection
 Defective products! Sulfur is prohibited!

answer:  

class Product { //Complete preparation
    boolean isDefect;
    String name;
    //Supplementary code
	public boolean isDefect() {
		return isDefect;
	}
	public void setIsDefect(boolean isDefect) {
		this.isDefect = isDefect;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
 }
class DefectException extends Exception { //Complete preparation
    String message;
   //Supplementary code
    DefectException(){
    }
    
     void toShow() {
    	System.out.print("Defective products!");
    }

 }
class Machine {
   public void checkProduct(Product product) throws DefectException {
      if(product.isDefect()) {
          DefectException defect=new DefectException();
          //[code 1] / / throw defect
          throw defect;
      }
      else {
          System.out.print(product.getName()+"Not defective! ");
      }
   }
 }

6-7 jmu-Java-06 exception - capture of multiple types of exceptions (10 points)

If the code in the try block may throw a variety of exceptions, and there may be inheritance between these exceptions, you need to pay attention to the capture order when capturing 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;
        }
        /*Put your answers here*/
    }//end while
    sc.close();
}

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

sample input

number illegal except quit

sample output

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

answer:  

	        catch(Exception e){
                if (choice.equals("number"))
                    System.out.println ("number format exception");
                if (choice.equals("illegal"))
                    System.out.println ("illegal argument exception");
                if (choice.equals("except"))
                    System.out.println ("other exception");
                System.out.println (e);
	        } 

Keywords: Java Eclipse pta

Added by jfdutcher on Wed, 13 Oct 2021 00:18:51 +0300