Java final sprint review

3, Interface and exception

  1. The following program throws an exception and catches it. Please replace [Code] with java code.
public class Main {
	static void proc() throws IllegalAccessException{
    	System.out.println("inside proc");
        throw new IllegalAccessException("demo");
    }
    public static void main(String[] args) {
		try {
			proc();
		}catch(IllegalAccessException e){
			System.out.println("capture"+e);
		}
	}
}
  1. Replace the [Code] part with Java code according to the requirements of the template
class NoLowerLeter extends Exception//Class declaration, declaring a subclass of Exception, NoLowerLetter
{
    public void print() {
        System.out.printf("%c",'#');
    }
}
class NoDigit extends Exception//Class declaration, declaring a subclass of Exception, NoDigit
{
    public void print() {
        System.out.printf("%c", '*');
    }
}
class People{
    void printLetter(char c) throws NoLowerLetter{
        if(c<'a'||c>'z') {
            NoLowerLetter noLowerLetter=new NoLowerLetter();//Create an object of type NoLowerLetter
            throw noLowerLetter;//Throw noLowerLetter
             }
        else {
            System.out.print(c);
        }
    }
    void printDigit(char c)throws NoDigit{
        if(c<'1'||c>'9') {
            NoDigit noDigit=new NoDigit();//Create an object of type NoDigit
            throw noDigit;//Throw noDigit
            }
        else {
            System.out.print(c);
        }
    }
}
public class Main{

    public static void main(String[] args) {
        People people=new People();
        for(int i=0;i<128;i++) {
            try {
                people.printLetter((char)i);
            }
            catch(NoLowerLetter e) {
                e.print();
            }
        }
        for(int i=0;i<128;i++) {
            try {
                people.printDigit((char)i);
            }
            catch(NoDigit e) {
                e.print();
            }
        }

    }
}
  1. Calculation results

The method of calculating 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 examines the examination of a subject in a class, it calculates the average score of the whole class. Gymnastics gym class and School class both implement the ComputerAverage interface, but the implementation methods are different.


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

//Define interface
interface ComputerAverage{
	public double average(double x[]);
}

//Define the interface implemented by the Gymnastics class
class Gymnastics implements ComputerAverage{

	@Override
	public double average(double[] x) {
		double max = x[0];
		double min = x[0];
		double sum = 0;
		int maxIndex = 0,minIndex = 0;
		for (int i = 0; i < x.length; i++) {
			sum += x[i];
			if(x[i] > max) {
				max = x[i];
				maxIndex = i;
			}
			if(x[i] < min) {
				min = x[i];
				minIndex = i;
			}
		}
		sum -= x[maxIndex];
		sum -= x[minIndex];
		return sum / (x.length-2);
	}
	
}
//Define the School class implementation interface
class School implements ComputerAverage{

	@Override
	public double average(double[] x) {
		double sum = 0;
		for (int i = 0; i < x.length; i++) {
			sum += x[i];
		}
		return sum / x.length;
	}
	
}
  1. Loading capacity of truck (15 points)
    The truck will carry a batch of goods, which are composed 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 this interface: Television, Computer, and WashMachine These three classes give self weight through the implementation 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; computeWeight() method of Computer returns 2 times the weight value; The computeWeight() method of WashMachine returns three times the weight value
    There is a Truck class, which 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.

    Example of referee test procedure:
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
         ComputerWeight[] goods=new ComputerWeight[650]; //650 goods
         double[] a=new double[3];//Store the initial value of the weight attribute 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

//The code for defining the interface ComputerWeight is written below
interface ComputerWeight{
	public double computeWeight();
}
//The ComputerWeight code that defines the implementation interface of class Television is written below
class Television implements ComputerWeight{
	
	double weight;

	public Television(double weight) {
		this.weight = weight;
	}

	@Override
	public double computeWeight() {
		return weight;
	}
	
}

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

	double weight;
	
	public Computer(double weight) {
		this.weight = weight;
	}

	@Override
	public double computeWeight() {
		return 2 * weight;
	}
	
}


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

	double weight;
	
	public WashMachine(double weight) {
		super();
		this.weight = weight;
	}

	@Override
	public double computeWeight() {
		return 3 * weight;
	}
	
}

//Class Truck, the implementation of the relevant member method code is written below
class Truck{
	
	ComputerWeight[] computerWeights;

	public Truck(ComputerWeight[] computerWeights) {
		this.computerWeights = computerWeights;
	}
	public void setGoods(ComputerWeight[] computerWeights) {
		this.computerWeights = computerWeights;
	}
	public double getTotalWeights() {
		double sum = 0;
		for (int i = 0; i < computerWeights.length; i++) {
			sum += computerWeights[i].computeWeight();
		}
		return sum;
	}
}
  1. 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 and implement the interface IShape. Radius r is a private member of the Circle class, which contains the constructor with parameter r.
    Define a Cone class Cone, in which there IS a member IS of IShape type and a member of Cone height h, including a construction method to assign initial values to IS and h, and a public double getVolume() method to calculate the volume of Cone

    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 */

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

	public double getPerimeter();
	public double getArea();
}
class RTriangle implements IShape{
	
	private double side1,side2;

	public double getSide1() {
		return side1;
	}

	public double getSide2() {
		return side2;
	}

	public void setSide1(double side1) {
		this.side1 = side1;
	}

	public void setSide2(double side2) {
		this.side2 = side2;
	}
	
	public RTriangle(double side1, double side2) {
		this.side1 = side1;
		this.side2 = side2;
	}

	@Override
	public double getPerimeter() {
		double side3 = Math.sqrt(side1*side1+side2*side2);
		return side1 + side2 + side3;
	}

	@Override
	public double getArea() {
		return side1 * side2 * 1/2;
	}
}

class Circle implements IShape{
	
	private double r;
	public final double PI = 3.14;
	public double getR() {
		return r;
	}
	public void setR(double r) {
		this.r = r;
	}
	public Circle(double r) {
		this.r = r;
	}

	@Override
	public double getPerimeter() {
		return 2 * PI *r;
	}

	@Override
	public double getArea() {
		return PI * r * r; 
	}
	
}

class Cone{
	
	double h;
	IShape IS;
	public Cone(IShape IS,double h) {
		this.IS = IS;
		this.h = h;
	}
	public double getVolume() {
		return IS.getArea() * h * 1.0/3;
	}
}
  1. 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
}
}

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 */

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("Cross-border 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
}
}
  1. 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. The message attribute of this subclass has the construction method DefectException() to assign the "defective" to the message member, and the toShow() method to output 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.
    Definition of design class:
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*/

class Product { //Complete preparation
    boolean isDefect;
    String name;
	public boolean isDefect() {
		return isDefect;
	}
	public String getName() {
		return name;
	}
	public void setIsDefect(boolean isDefect) {
		this.isDefect = isDefect;
	}
	public void setName(String name) {
		this.name = name;
	}
    


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

    public DefectException() {
	}
	public DefectException(String message) {
    	this.message = message;
    }
    public void toShow() {
		System.out.print("Defective products!");
	}


 }
class Machine {
   public void checkProduct(Product product) throws DefectException {
      if(product.isDefect()) {
          DefectException defect=new DefectException();
          throw defect;
      }
      else {
          System.out.print(product.getName()+"Not defective! ");
      }
   }
 }
  1. jmu-Java-06 exception - capture of various 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();
}

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

4, Object oriented advanced programming

  1. This problem requires that when the main thread exits, the thread t1 started in the main method should also end automatically.
public class Main {
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new PrintTask());
        t1.setDaemon(true);
        t1.start();
        System.out.println(Thread.currentThread().getName() + " end");
    }
}
  1. This topic requires t1 thread to print before executing the last sentence of the main method of the main thread out. println(Thread.currentThread(). getName()+" end");
public class Main {
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new PrintTask());
        t1.start();
        t1.join();
        System.out.println(Thread.currentThread().getName()+" end");
    }
}
  1. The following program uses the generic mechanism to create an array list object and add three elements to it. Use the iterator to traverse the array list. Please complete the program.
import java.util.*;
public class Main{
    public static void main(String[] args) {
        List<String> al=new ArrayList<String>(); 
        al.add("red");
        al.add("yellow");
        al.add("blue");
        ListIterator< String > listIter=al.listIterator(); 
        while(listIter.hasNext())
            System.out.print(listIter.next()+"  ");
    }
}
  1. jmu-Java-07 multithreading - mutually exclusive access

    Referee test procedure:
import java.util.Scanner;

/*Your code, that is, the code of the Account class*/

/*The system has code, so you don't need to pay attention*/
class Account{
	private int balance;
	public int getBalance() {
		return balance;
	}
    Account(int balance){
        this.balance = balance;
    }
	public synchronized void deposit(int money) {
		balance += money;
	}
	public synchronized void withdraw(int money) {
		balance -= money;
	}
}
  1. jmu-Java-07 multithreading - synchronous access

    Referee test procedure:
import java.util.Scanner;

//Here is the code of the first half of the existing Account class
/*Here is the deposit code*/
/*Here is the first half of the withraw code*/
    if(balance<0) //Here is the second half of the withraw code.
        throw new IllegalStateException(balance+"");    
    }

/*The system has code, so you don't need to pay attention*/
public void deposit(int money) {
		synchronized (this) {
			balance += money;
		}
	}
public void withdraw(int money) {
	synchronized (this) {
		balance -= money;
	}
  1. jmu-Java-05 deletion of specified elements in set List
    Write the following two functions
/*Take the space (single or multiple) as the separator to extract the elements in line and put them into a List*/
public static List<String> convertStringToList(String line) 
/*Remove the same elements as str contents from the list*/
public static void remove(List<String> list, String str)

Referee test procedure:

public class Main {

    /*covnertStringToList function code*/   

    /*remove function code*/

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

}

/*Take the space (single or multiple) as the separator to extract the elements in line and put them into a List*/
	public static List<String> convertStringToList(String line) {
        List<String> list = new ArrayList<String>();
		String[] str = line.split("\\s+");
		for (int i = 0; i < str.length; i++) {
			list.add(str[i]);
		}
		return list;
	}
	/*Remove the same elements as str contents from the list*/
	public static void remove(List<String> list, String str) {
		for (int i = 0; i < list.size(); i++) {
			if(list.get(i).equals(str)) {
				list.remove(i);
                i--;
			}
		}
	}
  1. Try multithreading (20 points)
    Write four threads. The first thread increases from 1 to 25, the second thread increases from 26 to 50, the third thread increases from 51 to 75, and the fourth thread increases from 76 to 100. Finally, add the calculation results of the four threads.
class Count extends Thread{
	
	int start;

	Count(int start) {
		this.start = start;
	}

	@Override
	public synchronized void run() {
		for (int i = start; i < start + 25; i++) {
			Main.sum += i;
		}
	}
}
public class Main{
	public static int sum = 0;
	public static void main(String[] args) throws Exception {
		Count count1 = new Count(1);
		Count count2 = new Count(26);
		Count count3 = new Count(51);
		Count count4 = new Count(76);
		count1.start();
		count1.join();
		count2.start();
		count2.join();
		count3.start();
		count3.join();
		count4.start();
		count4.join();
		System.out.println(sum);
	}
}
  1. Use of List (15 points)
    Use the exercise list.
    Define the Person class
    Define the private properties String name,int age, and use Eclipse to generate each property setter and getter, with parameter Person(String name,int age), no parameter construction method, and toString method.
    Define the main class in the main method
    Define list = new arraylist();
    Assign value to variable n with keyboard
    Generate n Person objects and add them to the list. The name and age of the Person are given through the keyboard
    Loop the list and output the information of all Person objects in the list (call the toString method)
import java.sql.Array;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

class Person{
	private String name;
	private int age;
	public String getName() {
		return name;
	}
	public int getAge() {
		return age;
	}
	public void setName(String name) {
		this.name = name;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public Person() {
	}
	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}
	@Override
	public String toString() {
		return "Person [name=" + getName() + ", age=" + getAge() + "]";
	}
}

public class Main{
	public static void main(String[] args) {
		List list = new ArrayList<>();
		Scanner input = new Scanner(System.in);
		int n = input.nextInt();
		for (int i = 0; i < n; i++) {
			Person person = new Person(input.next(),input.nextInt());
			list.add(person);
		}
		for (int i = 0; i < n; i++) {
			System.out.println(list.get(i).toString());
		}
	}
}

Tags: OOP interface

Posted by ridiculous on Sat, 07 May 2022 00:21:24 +0300