Java final sprint review (Part 2)

Bald bald bald bald 2022-02-13 07:15:26 阅读数:701

java final sprint review

3、 ... and 、 Interface and exception

  1. The following program throws an exception and catches it . Please replace 【 Code 】 by 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. According to the requirements of the template , take 【 Code 】 Part replaced with Java Code
class NoLowerLeter extends Exception// Class declaration , Make a statement Exception Subclasses of NoLowerLetter
{

public void print() {

System.out.printf("%c",'#');
}
}
class NoDigit extends Exception// Class declaration , Make a statement Exception Subclasses of 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();// establish NoLowerLetter Type object 
throw noLowerLetter;// Throw out noLowerLetter
}
else {

System.out.print(c);
}
}
void printDigit(char c)throws NoDigit{

if(c<'1'||c>'9') {

NoDigit noDigit=new NoDigit();// establish NoDigit Type object 
throw noDigit;// Throw out 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. Calculate the score

The method of calculating gymnasts' scores 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 , Is to calculate the average grade of the whole class . Artistic Gymnastics Gymnastics Classes and schools School Classes all implement ComputerAverage Interface , But in a different way .

 Insert picture description here
Sample 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 call average(double x[]) Method , Will array a Pass to parameter x
//System.out.printf("%n");
System.out.printf(" The gymnast finally scored :%5.3f\n",result);
computer=new School();
result=computer.average(b); //computer call average(double x[]) Method , Will array b Pass to parameter x
System.out.printf(" Average grade of class examination :%-5.2f",result);
}
}
/* Please fill in the answer here */
// Defining interfaces 
// Definition Gymnastics Class implementation interface 
// Definition School Class implementation interface 

 Insert picture description here

// Defining interfaces 
interface ComputerAverage{

public double average(double x[]);
}
// Definition Gymnastics Class implementation interface 
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);
}
}
// Definition 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. The loading capacity of the truck (15 branch )
    The truck has to carry a batch of goods , The goods consist of three commodities : TV 、 Computer 、 Washing machine . The truck needs to calculate the weight of the whole batch of goods .
    Ask for a ComputerWeight Interface , There is a method in this interface :
    public double computeWeight()
    ###### There are three classes that implement this interface :Television、Computer and WashMachine. These three classes are given by implementing the interface . this 3 Each class has properties weight, And initialize... Through the construction method , among Television Class computeWeight() Method , return weight value ;Computer Of computeWeight() Method , return 2 times weight value ;WashMachine Of computeWeight() Method , return 3 times weight value
    There's a truck Truck class , For this purpose ComputeWeight An array of interface types as members (Truck Class oriented interface ), Then the elements of the array can store Television References to objects 、Computer Object reference or WashMachine
    References to objects . Program can output Truck The total weight of the goods loaded by the object .
     Insert picture description here
    Sample referee test procedure :
import java.util.Scanner;
public class Main {

public static void main(String[] args) {

ComputerWeight[] goods=new ComputerWeight[650]; //650 Piece goods 
double[] a=new double[3];// Storage Television,Computer,WashMachine object weight Initial value of attribute 
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++) {
 // 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(" The weight of the goods loaded by the truck :%-8.5f kg\n",truck.getTotalWeights());
goods=new ComputerWeight[68]; //68 Piece goods 
for(int i=0;i<goods.length;i++) {
 // 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(" The weight of the goods loaded by the truck :%-8.5f kg\n",truck.getTotalWeights());
}
}
/* Please fill in the answer here */
// Definition Interface ComputerWeight The code is written below 
// Defining classes Television Implementation interface ComputerWeight The code is written below 
// Defining classes Computer Implementation interface ComputerWeight The code is written below 
// Defining classes WashMachine Implementation interface ComputerWeight The code is written below 
// class Truck , Implement related member methods The code is written below 

 Insert picture description here

// Definition Interface ComputerWeight The code is written below 
interface ComputerWeight{

public double computeWeight();
}
// Defining classes Television Implementation interface ComputerWeight The code is written below 
class Television implements ComputerWeight{

double weight;
public Television(double weight) {

this.weight = weight;
}
@Override
public double computeWeight() {

return weight;
}
}
// Defining classes Computer Implementation interface ComputerWeight The code is written below 
class Computer implements ComputerWeight{

double weight;
public Computer(double weight) {

this.weight = weight;
}
@Override
public double computeWeight() {

return 2 * weight;
}
}
// Defining classes WashMachine Implementation interface ComputerWeight The code 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 , Implement related member methods The 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 branch )
    Define an interface IgetArea, There are ways to double getArea(); Used to calculate shape area , Define another interface IgetPerimeter, There are ways to double getPerimeter(); Used to calculate the perimeter of a shape . Interface IShape There are constants PI=3.14, Inherit Interface IgetArea and IgetPerimeter
    Define a right triangle class (regular triangle)RTriangle class , Implementation interface IShape. Two right angled sides serve as Triangle A private member of a class , The parameters contained in the class are 2 Construction method of a right angle edge .
    Define a circular class Circle, Implementation interface IShape. radius r As Circle A private member of a class , The parameters contained in the class are r Construction method of .
    Define a cone class Cone , There is one in the class IShape Members of type IS, And cone height h Members of , Contains a constructor for IS and h Assign initial value to , There's another one public double getVolume() Method , Used to calculate the volume of the cone
     Insert picture description here
    Sample 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 */

 Insert picture description here

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. Standard exception classes commonly used in the system (10 branch )
    Common exception classes NumberFormatException,IndexOutOfBoundsException、ArithmeticException etc. , This program , Build a Test_Exception class , There's a test Method , It is used to detect the occurrence of the above abnormal objects and output corresponding information . For example, when NumberFormatException abnormal , Output " Data format is abnormal "; happen IndexOutOfBoundsException abnormal , Output " Out of bounds "; happen ArithmeticException abnormal , Output " Arithmetic operation exception ". ##.# 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;
}
//catch You need to fill in this section by yourself 
catch(...){
...}
catch(...){
...}
catch(...){
...}
catch(Exception e) {

System.out.println("Exception:"+e.getMessage());
} // First catch Subclass Exception, after catch Parent class 
}
}

Sample 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_Exception class */

 Insert picture description here

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;
}
//catch You need to fill in this section by yourself 
catch(NumberFormatException e){

System.out.println(" Data format is abnormal ");
}
catch(IndexOutOfBoundsException e){

System.out.println(" Out of bounds ");
}
catch(ArithmeticException e){

System.out.println(" Arithmetic operation exception ");
}
catch(Exception e) {

System.out.println("Exception:"+e.getMessage());
} // First catch Subclass Exception, after catch Parent class 
}
}
  1. Check whether the goods are defective (10 branch )
    Equipment for factory inspection of defective products , If it is found to be defective, issue a warning . Program simulation equipment to find defective process .
    Write a product class Product, There are member variables name and isDefect( Is it defective ), Yes get and set Method .
    Write a Exception Subclasses of DefectException, This subclass message attribute , There's a way to structure DefectException() take " Defective product " Assign a value to message member , Yes toShow() Method output message Value
    Write a Machine class , Methods of this class checkProduct(Product product) When parameters are found product When it is defective (product Of isDefect The attribute is true), Will throw out DefectException Exception object .
    The program is in the main class main Methods try…catch Of the statement try Partial let Machine Class checkProduct Method , If a defective product is found, it will be in try…catch Of the statement catch Partial disposal of defective products .
    Design class definition :
class Product {
 // Completely write 
boolean isDefect;
String name;
// Supplementary code 
}
class DefectException extends Exception {
 // Completely write 
String message;
// Supplementary code 
}
class Machine {

public void checkProduct(Product product) throws DefectException {

if(product.isDefect()) {

DefectException defect=new DefectException();
//【 Code 1】 // Throw out defect
}
else {

System.out.print(product.getName()+" Not defective ! ");
}
}
}

Sample 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 Piece 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()+" Inspection passed ");
}
catch(DefectException e) {

e.toShow();//【 Code 2】 //e call toShow() Method 
System.out.println(products[i].getName()+" Forbidden !");
}
}
}
}
/* Will be complete Product class , DefectException class and Machine Class is written below */

 Insert picture description here

class Product {
 // Completely write 
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 {
 // Completely write 
String message;
public DefectException() {

}
public DefectException(String message) {

this.message = message;
}
public void toShow() {

System.out.print(" Defective product !");
}
}
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 abnormal - Catch multiple types of exceptions (10 branch )
    If try The code in the block may throw a variety of exceptions , And there may be inheritance between these exceptions , When catching exceptions, you need to pay attention to the capture order .
    Complete the following code , 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 answer here */
}//end while
sc.close();
}

 Insert picture description here

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

Four 、 Object oriented advanced programming

  1. When the main thread exits , stay main Method t1 It also ends 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 After the thread finishes printing , To execute the main thread main The last sentence of the method System.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 procedure .
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 - Exclusive access
     Insert picture description here
    Referee test procedure :
import java.util.Scanner;
/* Your code , namely Account Class code */
/* The system has code , No need for 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
     Insert picture description here
    Referee test procedure :
import java.util.Scanner;
// Here is what we already have Account The code of the first half of the class 
/* Here is deposit Code */
/* Here is withdraw The first half of the code */
if(balance<0) // Here is withdraw The second half of the code .
throw new IllegalStateException(balance+"");
}
/* The system has code , No need for attention */
public void deposit(int money) {

synchronized (this) {

balance += money;
}
}
public void withdraw(int money) {

synchronized (this) {

balance -= money;
}
  1. jmu-Java-05 aggregate -List Deletion of specified elements in
    Write the following two functions
/* With spaces ( One or more ) Separator , take line Extract the elements in , Put one in List*/
public static List<String> convertStringToList(String line)
/* stay list Remove and str Elements with the same content */
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();
}
}

 Insert picture description here

/* With spaces ( One or more ) Separator , take line Extract the elements in , Put one in 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;
}
/* stay list Remove and str Elements with the same content */
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 branch )
    To write 4 Threads , The first thread starts from 1 Add to 25, The second thread starts from 26 Add to 50, The third thread starts from 51 Add to 75, The fourth thread starts from 76 Add to 100, Finally, add the results calculated by the four threads .
     Insert picture description here
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. List Use (15 branch )
    Use the exercise list for this question .
    Definition Person class
    Define private properties String name,int age, Use Eclipse Generate each attribute setter 、getter, Ginseng Person(String name,int age) 、 No arguments Construction method ,toString Method .
    Definition Main class , stay main In the method
    Definition List list = new ArrayList();
    Use the keyboard to give variables n assignment
    Generate n individual Person Object and add it to the list , The Person Of name and age Give... Through the keyboard
    Loop list , Output list all Person Object information ( call toString Method )
     Insert picture description here
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());
}
}
}
copyright:author[Bald bald bald bald],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/02/202202130715227495.html