JavaSE exercises - Advanced Topics

Posted by aahh on Tue, 18 Jan 2022 15:29:00 +0100

Chapter XIII

First question

Case: the child thread outputs an even number between 1-100, and the main thread outputs an odd number between 1-100.

The effects are as follows:

package com.atguigu.test01;
​
public class Test01 {
    public static void main(String[] args) {
        new Thread("Child thread"){
            public void run(){
                for (int i = 0; i <= 100; i+=2) {
                    System.out.println(getName() + "-->" + i);
                }
            }
        }.start();
        
        for (int i = 1; i <= 100; i+=2) {
            System.out.println("main Main thread -->" + i);
        }
    }
}
​

Second question

Case: create and start two sub threads, one printing odd numbers between 1-10 and one printing even numbers between 1-10.

(1) Each thread is required to either not print or print 5 consecutive numbers, with an interval of 500 milliseconds

(2) However, the two threads do not require alternate printing.

The effects are as follows:

package com.atguigu.test02;
​
public class Test02 {
    public static void main(String[] args) {
        new PrintEven().start();
        new PrintOdd().start();
    }
}
class PrintEven extends Thread{
    private int num = 1;
    public void run(){
        while(true){
            synchronized (Thread.class) {
                for (int i = 1; i <= 5; i++) {
                    num+=2;
                    System.out.println("Even threads, 2nd" + i + "Number:" + num);
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            
        }
    }
}
class PrintOdd extends Thread{
    private int num = 2;
    public void run(){
        while(true){
            synchronized (Thread.class) {
                for (int i = 1; i <= 5; i++) {
                    num+=2;
                    System.out.println("Odd threads, 2nd" + i + "Number:" + num);
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

Question 3

Case: create and start 2 sub threads, one printing odd number and one printing even number.

(1) Alternate printing is required.

(2) Each number is printed at an interval of 1 second

The effects are as follows:

package com.atguigu.test03;
​
public class Test03 {
    public static void main(String[] args) {
        new PrintNumber().start();
        new PrintNumber().start();
    }
}
class PrintNumber extends Thread{
    private static int num;
    public void run(){
        while(true){
            synchronized (PrintNumber.class) {
                try {
                    PrintNumber.class.notify();
                    Thread.sleep(1000);
                    System.out.println(getName() + ":" + ++num); 
                    PrintNumber.class.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Question 4

Case:

1. Create a bank account class,

(1) Attribute: account number, balance,

(2)get/set,

(3) toString(): Return: Account: xxx, balance: xxx

2. Create a husband class

Be responsible for saving money inside, and each deposit is within [010000]

3. Create a wife class

Be responsible for withdrawing money, ranging from [010000] each time. If the balance is insufficient, you can't withdraw it until your husband has saved enough

package com.atguigu.test04;
​
public class Test04 {
    public static void main(String[] args) {
        Account a = new Account("1122",0);
        
        new Wife(a).start();
        new Husband(a).start();
    }
}
class Account{
    private String id;
    private double balance;
    public Account(String id, double balance) {
        super();
        this.id = id;
        this.balance = balance;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public double getBalance() {
        return balance;
    }
    public void setBalance(double balance) {
        this.balance = balance;
    }
    @Override
    public String toString() {
        return "Account:" + id + ",Balance:" + balance ;
    }
}
class Wife extends Thread{
    private Account account;
    
    public Wife(Account account) {
        super();
        this.account = account;
    }
​
    public void run(){
        while(true){
            synchronized (Thread.class) {
                double money = Math.random() * 10000;
                while(money > account.getBalance()){
                    System.out.println("The wife wants to withdraw money this time:" + money +",But the balance is not enough, waiting...");
                    try {
                        Thread.class.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("The wife began to withdraw money. Current account status:" + account);
                System.out.println("The wife withdraws money this time:" + money);
                account.setBalance(account.getBalance() - money);
                System.out.println("The wife's withdrawal is over, and the current account status is:" + account);
                System.out.println();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            
        }
    }
}
class Husband extends Thread{
    private Account account;
    
    public Husband(Account account) {
        super();
        this.account = account;
    }
​
    public void run(){
        while(true){
            synchronized (Thread.class) {
                double money = Math.random() * 10000;
                System.out.println("Husband started saving money, current account status:" + account);
                System.out.println("The husband saved money this time:" + money);
                account.setBalance(account.getBalance() + money);
                System.out.println("Husband starts and ends, current account status:" + account);
                System.out.println();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Thread.class.notify();
            }
            
        }
    }
}

Question 5

Case: please write a multithreaded application as required to simulate multiple people passing through a cave:

1. This cave can only pass through one person at a time, and the time for each person to pass through the cave is 5 seconds;

2. Randomly generate 10 people and prepare this cave at the same time

3. Define a variable to record the number of people passing through the tunnel

4. Display the name of the person who passes through the cave each time and the passing order;

Description of operation steps

1. Define a tunnel class to implement the Runnable interface:

1.1 define a variable to record the number of people passing through the tunnel;

1.2 rewrite the run method of Runnable;

1.3 define a synchronization method to simulate that it takes 5 seconds for everyone to pass through the tunnel:

1.3.1 print "xx starts to pass through the tunnel..."

1.3.2 the sub thread sleeps for 5 seconds, and it takes 5 seconds to simulate everyone passing through the tunnel;

1.3.3 person times of change;

1.3.4 print the thread name and its sequence through the tunnel, and simulate the human passing through the tunnel and its sequence;

1.4 call the method through the tunnel;

2. Define a test class:

        2.1. Create a tunnel class object in the main method;

        2.2. In the main method, 10 sub thread objects are created in a loop, and the tunnel object is created through the construction method

And the thread name (as the person's name), and start the child thread;

package com.atguigu.test05;
​
public class Tunnel implements Runnable {
    // 1.1 define a variable to record the number of people passing through the tunnel
    private int crossNum = 0;
​
    /*
     * 1.2 Override the run method of Runnable
     */
    @Override
    public void run() {
        // 1.4 calling methods through tunnels
        cross();
    }
​
    /*
     * 1.3 Define a synchronization method to simulate that it takes 5 seconds for everyone to pass through the tunnel
     */
    public synchronized void cross() {
        //1.3.1 printing xx starts through the tunnel
        System.out.println(Thread.currentThread().getName() + "Start through the tunnel...");
        // 1.3.2 the sub thread sleeps for 5 seconds, and it takes 5 seconds to simulate everyone passing through the tunnel
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 1.3.3 person times of change
        crossNum++;
        // 1.3.4 print the thread name and its sequence through the tunnel, and simulate the human passing through the tunnel and its sequence
        System.out.println(Thread.currentThread().getName() + "Through the tunnel, TA Yes" + crossNum + "Yes!");
    }
}
​
package com.atguigu.test05;
​
public class Test05 {
    public static void main(String[] args) {
        // 2.1 create a tunnel class object in the main method
        Tunnel tul = new Tunnel();
​
        // 2.2 in the main method, create 10 sub thread objects in a loop, pass in the tunnel object and / / thread name (as the person's name) through the construction method, and start the sub thread
        for (int i = 1; i <= 10; i++) {
            Thread t = new Thread(tul, "p" + i);
            t.start();
        }
    }
}

Chapter 14

First question

There is an array a[1000] to store 0-999. It is required to delete one number every two numbers, and cycle to the beginning at the end to continue running. Find the original subscript position of the last deleted number.

Take 8 numbers as an example:

{0,1,2,3,4,5,6,7}: 0 - > 1 - > 2 (deleted) - > 3 - > 4 - > 5 (deleted) - > 6 - > 7 - > 0 (deleted)...

/*
 * There is an array a[1000] to store 0-999. It is required to delete one number every two numbers, and cycle to the beginning at the end to continue running. Find the original subscript position of the last deleted number.
​
Take 8 numbers as an example:
​
{0,1,2,3,4,5,6,7}: 0->1->2(Delete - > 3 - > 4 - > 5 (delete) - > 6 - > 7 - > 0 (delete)...
 */
public class TestHomework1 {
    public static void main(String[] args) throws InterruptedException {
        int[] a = new int[1000];
        for (int i = 0; i < a.length; i++) {
            a[i] = i;
        }
        
        int i=0;
        int count = 0;
        int delNum = 0;//Number of deleted numbers
        while(true) {
            if(a[i]!=-1) {//The deleted number will no longer be counted into the count number
                count++;
            }
            if(count==3) {//Two apart, delete the third
                a[i]=-1;//a[i]=-1, indicating the number deleted
                count=0;//Count re count
                delNum++;//Several statistics have been deleted
            }
            if(delNum==a.length-1) {//Leave the last to end the deletion process
                break;
            }
            if(++i==a.length) {//If the subscript has moved to the right, start from the beginning
                i=0;
            }
        }
        
        for (int j = 0; j < a.length; j++) {
            if(a[j]!=-1) {
                System.out.println("The last number deleted is: a[j]=" + a[j] + ",Its subscript:" + j);
            }
        }
    }
}

Second question

public static int binarySearch(int[] intsArray, int des) {
        int left = 0;
        int right = intsArray.length-1;
        int mid = (left + right)/2;
        while(left<=right) {
            if(intsArray[mid]==des) {
                return mid;
            }else if(des>intsArray[mid]){
                left = mid+1;
            }else {
                right=mid-1;
            }
            mid = (left + right)/2;
        }
        return -1;
    }

Question 3

public static int binarySearch(String[] intsArray, String des) {
        int left = 0;
        int right = intsArray.length-1;
        int mid = (left + right)/2;
        while(left<=right) {
            if(intsArray[mid].equals(des)) {
                return mid;
            }else if(des.compareTo(intsArray[mid])>0){//String comparison method
                left = mid+1;
            }else {
                right=mid-1;
            }
            mid = (left + right)/2;
        }
        return -1;
    }

Question 4

public static void main(String[] args) throws InterruptedException {
        System.out.println(Arrays.toString(suShu(10)));
    }
    
    public static int[] suShu(int n){
        int[] arr = new int[n];
        
        int index=0;
        for (int i = 1; i < n; i++) {
            boolean flag = true;
            for (int j = 2; j < i; j++) {
                if(i%j==0) {
                    flag=false;
                    break;
                }
            }
            if(flag) {
                arr[index++] = i;
            }
        }
        return Arrays.copyOf(arr, index);
    }

Question 5

public static void main(String[] args) throws InterruptedException {
        int[] arr = {1,2,3,4,5,6,7};
        arr = changPosition(1,5,arr);
        System.out.println(Arrays.toString(arr));
    }
    
    public static int[] changPosition(int n1,int n2,int[] ii) {
        int indexN1=-1;
        for (int i = 0; i < ii.length; i++) {
            if(ii[i]==n1) {
                indexN1 = i;
                break;
            }
        }
        int indexN2 = -1;
        for (int i = 0; i < ii.length; i++) {
            if(ii[i]==n2) {
                indexN2 = i;
                break;
            }
        }
        System.arraycopy(ii, indexN1+1, ii, indexN1, indexN2-indexN1);
        ii[indexN2]=n1;
        return ii;
    }

Question 6

import java.util.Arrays;
​
public class TestHomework6 {
    public static void main(String[] args) {
        int[] arr = {0,1,2,3,4,5,6,7,8,9};
        
        int m = 10;
        for (int i = 0; i < m; i++) {
            move(arr);
            System.out.println(Arrays.toString(arr));
        }
        
        int value = 5;
        System.out.println(indexOf(arr, m, value));
    }
    
    public static int indexOf(int[] arr,int m, int value) {
        while(m>arr.length) {
            m = m - arr.length;
        }
        if(value == arr[0]) {
            return 0;
        }else if(value > arr[0]) {
            return Arrays.binarySearch(arr, 1, m, value);
        }else {
            return Arrays.binarySearch(arr, m, arr.length, value);
        }
    }
    
    public static void move(int[] arr) {
        int temp = arr[arr.length-1];
        System.arraycopy(arr, 0, arr, 1, arr.length-1);
        arr[0] = temp;
    }
}

Chapter 15

Code programming problem

First question

  • Reverses the string entered on the keyboard.

  • Code implementation, and the reference effect is shown in the figure:

package com.atguigu.test01;
​
import java.util.Scanner;
​
public class Test01 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Please enter a string from the keyboard:");
        String str = input.next();
        
        StringBuilder s = new StringBuilder(str);
        str = s.reverse().toString();
        System.out.println("After reversal:" + str);
        input.close();
    }
}
​

Second question

  • Enter the QQ number on the keyboard to verify the correctness of the format.

    • Must be 5-12 digits.

    • 0 cannot start.

  • Code implementation, and the reference effect is shown in the figure:

package com.atguigu.test02;
​
import java.util.Scanner;
​
public class Test02 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Please enter qq Number:");
        String qq = input.next();
        
        System.out.print("this qq Whether the number is correct:");
        if(qq.matches("[1-9][0-9]{4,11}+")){
            System.out.println(true);
        }else{
            System.out.println(false);
        }
        input.close();
    }
}

Question 3

  • String lookup.

    • Enter a large string and then a small string on the keyboard.

    • Counts the number of occurrences of small strings in large strings.

  • Code implementation, and the effect is shown in the figure:

package com.atguigu.test03;
​
import java.util.Scanner;
​
public class Test03 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Please enter a large string:");
        String big = input.next();
        
        System.out.print("Please enter a small string:");
        String small = input.next();
        
        int index;
        int count = 0;
        while((index = big.indexOf(small))!=-1){
            big = big.substring(index+small.length());
            count++;
        }
        System.out.println(small + "There it is" +count + "second");
        
        input.close();
    }
}
​

Question 4

  • Replace a string in a string.

    • Enter an srcStr string on the keyboard, and then enter a delStr string.

    • Delete all delStr strings in the word srcStr string.

    • And count the number of occurrences of delStr string in srcStr

  • Code implementation, part of the effect is shown in the figure:

package com.atguigu.test04;
​
import java.util.Scanner;
​
public class Test04 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        
        System.out.print("Please enter the original string:");
        String src = input.next();
        
        System.out.print("Please enter the string to delete:");
        String del = input.next();
        
        String result = src.replaceAll(del, "");
        
        int count = (src.length() - result.length())/del.length();
        System.out.println(del+"A total of:" + count + "second");
        System.out.println("delete" + del + "Post string:" + result);
        
        input.close();
    }
}
​

Question 5

  • Generate a random decimal within 100 and convert it into a string with two decimal places, regardless of rounding.

  • Code implementation, and the effect is shown in the figure:

package com.atguigu.test05;
​
public class Test05 {
    public static void main(String[] args) {
        double num = Math.random() * 100;
        System.out.println("The random number is:" +num);
        String str = num + "";
        str = str.substring(0,str.indexOf(".") + 3);
        System.out.println("After two decimal places, it is:" + str);
    }
}

Question 6

  • Filter string.

    • Define an array and store multiple strings.

    • Delete strings longer than 5 and print the deleted array.

  • Code implementation, and the effect is shown in the figure:

package com.atguigu.test06;
​
import java.util.Arrays;
​
public class Test06 {
    public static void main(String[] args) {
        String[] arr = {"helloworld","java","chai","atguigu","lin","yan","Iloveyou"};
        
        System.out.println("Original string:");
        System.out.println( Arrays.toString(arr));
        int index = 0;
        while(index < arr.length){
            if(arr[index].length()>5){
                System.arraycopy(arr, index+1, arr, index, arr.length-index-1);
                arr = Arrays.copyOf(arr, arr.length-1);
            }else{
                index++;
            }
        }
        System.out.println("After deletion:");
        System.out.println(Arrays.toString(arr));
    }
}
​

Question 7

  • Determine palindrome string. If a string is read from front to back and from back to front, it is a string called palindrome string, such as mom, dad and noon.

  • Code implementation, and the effect is shown in the figure:

package com.atguigu.test07;
​
import org.junit.Test;
​
public class Test07 {
    @Test
    public void test01() {
        String str = "noon";
        System.out.println(str);
        StringBuilder s = new StringBuilder(str);
        String string = s.reverse().toString();
        System.out.print("Number of palindromes:");
        if(str.equals(string)){
            System.out.println(true);
        }else{
            System.out.println(false);
        }
    }
​
    @Test
    public void test02() {
        String str = "noon";
        System.out.println(str);
        char[] arr = str.toCharArray();
        boolean flag = true;
        for (int left = 0,right=arr.length-1; left <=right; left++,right--) {
            if(arr[left] != arr[right]){
                flag = false;
                break;
            }
        }
        System.out.print("Number of palindromes:");
        if(flag){
            System.out.println(true);
        }else{
            System.out.println(false);
        }
    }
}
 

Question 8

  • Verify whether the password is legal.

    • Must be at least 9 characters.

    • Must be at least 2 uppercase characters.

    • Must contain lowercase letters and numbers.

  • Code implementation, and the effect is shown in the figure:

package com.atguigu.test08;
​
import org.junit.Test;
​
public class Test08 {
    @Test
    public void test01(){
        String password = "at1Gui2Gu";
        
        char[] arr = password.toCharArray();
        int upCount = 0;
        int numCount = 0;
        int lowerCount = 0;
        for (int i = 0; i < arr.length; i++) {
            if(arr[i]>='A' && arr[i]<='Z'){
                upCount++;
            }else if(arr[i]>='a' && arr[i]<='z'){
                lowerCount++;
            }else if(arr[i]>='0' && arr[i]<='9'){
                numCount++;
            }
        }
        System.out.print(password+"Legal:");
        if(password.length() >=9 && upCount>=2 && numCount!=0 && lowerCount!=0){
            System.out.println(true);
        }else{
            System.out.println(false);
        }
        
    }
}
​

Question 9

  • Simulate user login.

    • Define the user class, and the attributes are user name and password.

    • Use an array to store multiple user objects.

    • Enter the user and password, compare the user information, match successfully, login successfully, otherwise login fails.

    • When login fails, when the user name is wrong, it will prompt that there is no such user.

    • When the login fails, when the password is wrong, it will prompt that the password is wrong.

  • Code implementation, and the effect is shown in the figure:

package com.atguigu.test09;

import java.util.Scanner;

public class Test09 {
	public static void main(String[] args) {
		User[] all = new User[3];
		all[0] = new User("atguigu","123");
		all[1] = new User("chailinyan","8888");
		all[2] = new User("java","6666");
		for (int i = 0; i < all.length; i++) {
			System.out.println(all[i]);
		}
		
		Scanner input =new Scanner(System.in);
		System.out.print("Please enter user name:");
		String username = input.next();
		System.out.print("Please input a password:");
		String password = input.next();
		
		boolean flag = false;
		for (int i = 0; i < all.length; i++) {
			if(all[i].getUsername().equals(username) && all[i].getPassword().equals(password)){
				flag = true;
				break;
			}
		}
		System.out.println("Login results:" +flag);
		input.close();
	}
}
class User{
	private String username;
	private String password;
	public User(String username, String password) {
		super();
		this.username = username;
		this.password = password;
	}
	public User() {
		super();
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	@Override
	public String toString() {
		return username + "-" + password;
	}
	
}

Question 10

  • Define the Handleable interface, with an abstract method for handling string numbers, String handleString(String num);

    • Processing method 1: take the integer part.

    • Processing method 2: keep refers to positioning decimal and rounding.

  • Code implementation, and the effect is shown in the figure:

Development tips:

  • Call all abstract methods by anonymous inner classes.

 

Question 11

Case: there is a String abc = "342567891". Please write a program to ascending the String abc. You can use the existing function methods in JDK API.

package com.atguigu.test11;

import java.util.Arrays;

public class Test11 {
	public static void main(String[] args) {
		String abc = "342567891";
		char[] arr = abc.toCharArray();
		Arrays.sort(arr);
		abc = new String(arr);
		System.out.println(abc);
	}
}

package com.atguigu.test10;

public interface Handleable {
	String handleString(String num);
}

package com.atguigu.test10;

import org.junit.Test;

public class Test01 {
	@Test
	public void test01(){
		String str = "23.23456789";
		System.out.println("Original number:" + str);
		/*
		str = new Handleable() {
			@Override
			public String handleString(String num) {
				//Find decimal point position
				int index = num.indexOf(".");
				if(index != -1){
					num = num.substring(0, num.indexOf("."));
				}
				return num;
			}
		}.handleString(str);*/
        
        Handleable h = new Handleable() {
			@Override
			public String handleString(String num) {
				//Find decimal point position
				int index = num.indexOf(".");
				if(index != -1){
					num = num.substring(0, num.indexOf("."));
				}
				return num;
			}
		};
        str = h.handleString(str);
		
		System.out.println("After rounding:" + str);
	}
	@Test
	public void test03(){
		String str = "23.99996789";
		System.out.println("Original number:" + str);
		
		final int wei = 4;//Truncate to 4 decimal places and round
		str = new Handleable() {
			@Override
			public String handleString(String num) {
				BigDecimal big = new BigDecimal(num);
				BigDecimal b = new BigDecimal("1");
				BigDecimal shang = big.divide(b, wei, BigDecimal.ROUND_HALF_UP);
				return shang.toString();
			}
		}.handleString(str);
		System.out.println(str);
	}

Question 12

Case:

A known string String str = "1. hello 2. world 3. java 4.String 5. haha 6. HELLO";

It is required to count the letters with the most occurrences and their occurrences. Case insensitive.

package com.atguigu.test12;

import org.junit.Test;

public class Test12 {
	@Test
	public void test1(){
		String str = "1, hellao 2. world 3. java 4.String 5. haha 6,HELLO";
        
		//Convert the string to lowercase because it is not case sensitive and convenient for statistics
		str = str.toLowerCase();
        //Remove the non letters from it
        str = str.replaceAll("[^a-z]","");
		//Convert to character array
		char[] arr = str.toCharArray();
		//Count the number of occurrences of each letter
		int[] counts = new int[26];//Record the number of 26 letters
        /*
        counts[0]Number of times to save 'a' = 97-97 - > 0
        counts[1]Number of times to save 'b' = 98-97 - > 1
        */
		for (int i = 0; i < arr.length; i++) {
			counts[arr[i]-97]++;
		}
		
		//Find maximum value
		int max = counts[0];
		for (int i = 1; i < counts.length; i++) {
			if(max < counts[i]){
				max = counts[i];
			}
		}
		//Print maximum and letters
		for (int i = 0; i < counts.length; i++) {
			if(counts[i] == max){
                //I = 0 'a' letter
                //I = 1 'B' letter
				System.out.println(((char)(i+97)) + "There it is" + max + "second");
			}
		}
	}
	
}

Question 13

Case: known String str = "1.hello2.world3.java4.string"; It is required to split each word and traverse the display

package com.atguigu.test13;

public class Test13 {
	public static void main(String[] args) {
		String str = "1.hello2.world3.java4.string";
		//Put the first 1 Remove
        str = str.replaceAll("^\\d\\.","");
		//According to the numbers Split in the format of
		String[] split = str.split("\\d\\.");
		for (int i = 0; i < split.length; i++) {
			System.out.println(split[i]);
		}
	}
}

Code reading questions

Question 14

public static void main(String[] args) {
		String str = new String("world");
		char[] ch = new char[]{'h','e','l','l','o'};
		change(str,ch);
		System.out.println(str);
		System.out.println(String.valueOf(ch));
	}
	public static void change(String str, char[] arr){
		str = "change";
		arr[0] = 'a';
		arr[1] = 'b';
		arr[2] = 'c';
		arr[3] = 'd';
		arr[4] = 'e';
	}
package com.atguigu.test14;

public class Test14 {
	public static void main(String[] args) {
		String str = new String("world");
		char[] ch = new char[]{'h','e','l','l','o'};
		change(str,ch);
		System.out.println(str);//world
		System.out.println(String.valueOf(ch));//abcde
	}
	/*
	 * Method parameter: the reference data type passes the object address
	 * But string objects are immutable
	 */
	public static void change(String str, char[] arr){
		str = "change";
		arr[0] = 'a';
		arr[1] = 'b';
		arr[2] = 'c';
		arr[3] = 'd';
		arr[4] = 'e';
	}
}

Question 15

public class Test {
	int a;
	int b;
    String str;
	public void f(){
		a = 0;
		b = 0;
        str = "hello";
		int[] c = {0};
		g(b,c);
		System.out.println(a + " " + b + " " + c[0] + "," + str);
	}
	public void g(int b, int[] c,String s){
		a = 1;
		b = 1;
		c[0] = 1;
        s = "world";
	}
	public static void main(String[] args) {
		Test t = new Test();
		t.f();
	}
}
package com.atguigu.test17;

public class Test {
	int a;
	int b;
    String str;
	public void f(){
		a = 0;//Member variable this a--> t.a = 0
		b = 0;//Member variable this b --> t.b = 0
        str = "hello";//Member variable this str -> t.str = "hello"
		int[] c = {0}; //The local variable of the f() method is an array
		g(b,c,str);//this.g(b,c,str);
		System.out.println(a + " " + b + " " + c[0] + "," + str);//101hello
	}
	/*
	 * Parameter basic data type: pass data value
	 * Parameter reference data type: address value is passed, but string object is immutable
	 */
	public void g(int b, int[] c,String s){
		a = 1;//Modify the member variable this a -> t.a = 1
		b = 1;//Modify parameter b, local variable, (1) it has nothing to do with member variable b, (2) because b is the basic data type, it has nothing to do with argument b
		c[0] = 1;//c is an array and a reference data type. Modifying an element will affect the argument
        s = "world";//s is a local variable, but the string object is immutable and independent of arguments
	}
	public static void main(String[] args) {
		Test t = new Test();//t.a = 0, t.b = 0,  t.str = null
		t.f();
	}
}

Question 16

package com.atguigu.test18;

public class Test18 {
	/*
	 * The formal parameter is a reference data type, and the actual parameter passes an address value
	 */
	private static void change(String s,StringBuffer sb){
		s = "aaaa";//The string object is immutable. Once it is modified, it is a new object
		sb.setLength(0);//Empty the contents of sb first
		sb.append("aaaa");//Re splice aaaa
	}
	
	
	public static void main(String[] args) {
		String s = "bbbb";
		StringBuffer sb = new StringBuffer("bbbb");
		change(s,sb);
		System.out.println(s+sb);//bbbbaaaa
	}
}

Question 17

package com.atguigu.test19;

public class Example {
	String str = new String("good");
	char[] ch = {'a','b','c'};
	
	public static void main(String[] args) {
		Example ex = new Example();//ex.str = good   ex.ch=  abc
		
		ex.change(ex.str,  ex.ch);
		System.out.print(ex.str + " and ");//good + and + gbc
		System.out.print(ex.ch);
	}
	
	public void change(String str, char[] ch){//Parameter and argument point to the same array
		str = "test ok";//The string object is immutable, and the modification of formal parameters is independent of arguments
		ch[0] = 'g';//The modification of a formal parameter to an element directly modifies the value of an argument element
	}
}

Question 18

package com.atguigu.test20;

public class Test20 {
	public static void main(String[] args) {
		StringBuffer a = new StringBuffer("A");
		StringBuffer b = new StringBuffer("B");

		operate(a, b);

		System.out.println(a + "," + b);// AB , B
	}

	public static void operate(StringBuffer x, StringBuffer y) {
		x.append(y);// Equivalent to a splice b x = AB
		y = x;// Once the address value of the formal parameter is modified, it has nothing to do with the argument, that is, the formal parameter is re pointed to the new object
        y.append('x');
	}
}

Question 19

package com.atguigu.test21;

class TEXT{
	public int num;
	public String str;
	
	public TEXT(int num, String str){
		this.num = num;
		this.str = str;
	}
}
public class Class4 {
    //tIn is the address of the transfer object. Modifying the properties of the formal parameter will affect the actual parameter
    //intIn is passed data, and the modification of formal parameters of basic data type is independent of actual parameters
    //Integer and String objects are immutable
	public static void f1(TEXT tIn, int intIn, Integer integerIn, String strIn){
		tIn.num =200;
		tIn.str = "bcd";//The formal parameter and the argument point to the same TEXT object. Modifying the attribute is equivalent to modifying the attribute of the argument object
		intIn = 200;//A formal parameter of a basic data type is a "copy" of an argument. No matter how it is modified, it has nothing to do with the argument
		integerIn = 200;//Integer objects, like String objects, are immutable. Once modified, they are new objects and have nothing to do with arguments
		strIn = "bcd";
	}
	public static void main(String[] args) {
		TEXT tIn = new TEXT(100, "abc");//tIn.num = 100, tIn.str="abc"
		int intIn = 100;
		Integer integerIn = 100;
		String strIn = "abc";
		
		f1(tIn,intIn,integerIn,strIn);
		
		System.out.println(tIn.num + tIn.str + intIn + integerIn + strIn);
		//200 + bcd + 100 + 100 + abc
	}
}

Question 20

package com.atguigu.test22;

public class Test22 {
	/*
	 * GBK,UTF-8,ISO8859-1 All character encodings are downward compatible with ASCII codes
	 */
	public static void main(String[] args) throws Exception {
		String str = "China";
		System.out.println(str.getBytes("ISO8859-1").length);// 2
		// ISO8859-1 treats all characters as a byte and cannot handle multiple bytes
		System.out.println(str.getBytes("GBK").length);// 4 each Chinese character corresponds to 2 bytes
		System.out.println(str.getBytes("UTF-8").length);// 6 conventional Chinese is 3 bytes

		/*
		 * No garbled Code: (1) ensure that the encoded and decoded character set names are the same (2) no missing bytes
		 */
		System.out.println(new String(str.getBytes("ISO8859-1"), "ISO8859-1"));// Garbled code
		System.out.println(new String(str.getBytes("GBK"), "GBK"));// China
		System.out.println(new String(str.getBytes("UTF-8"), "UTF-8"));// China
	}
}

Chapter 16

day18_ After class practice

Generic exercises

Question 1

Case: there are four students' scores as follows:

(1) Use the Comparable interface to sort the scores of the following four students in descending order. If the scores are the same, sort them according to their age on the basis of score sorting. Please specify generics correctly

(2) Use Comparator to sort by name. Please specify generics correctly

(3) The effect is as follows

package com.atguigu.test01;
​
import java.util.Comparator;
import java.util.TreeSet;
​
public class Test01 {
    public static void main(String[] args) {
        System.out.println("Sort by grades and age:");
        TreeSet<Student> set = new TreeSet<>();
        set.add(new Student("liusan",20,90.0));
        set.add(new Student("lisi",22,90.0));
        set.add(new Student("wangwu",20,99.0));
        set.add(new Student("sunliu",22,100.0));
        for (Student student : set) {
            System.out.println(student);
        }
        
        System.out.println("Sort by name:");
        TreeSet<Student> all = new TreeSet<>(new Comparator<Student>() {
​
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        all.addAll(set);
        
        for (Student student : all) {
            System.out.println(student);
        }
    }
}
class Student implements Comparable<Student>{
    private String name;
    private int age;
    private double score;
    public Student(String name, int age, double score) {
        super();
        this.name = name;
        this.age = age;
        this.score = score;
    }
    public Student() {
        super();
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public double getScore() {
        return score;
    }
    public void setScore(double score) {
        this.score = score;
    }
    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + ", score=" + score + "]";
    }
    @Override
    public int compareTo(Student stu) {
        if(this.getScore()>stu.getScore()){
            return -1;
        }else if(this.getScore() < stu.getScore()){
            return 1;
        }
        return this.getAge() - stu.getAge();
    }
    
}

Question 2

Case:

1. Declare a coordinate class coordinate < T >, which has two attributes: X and y, both of which are of type T

2. In the test class, create two different coordinate class objects, specify the T type as String and Double, assign values to X and y, and print the object

package com.atguigu.test02;
​
public class Test02 {
    public static void main(String[] args) {
        Coordinate<Double> c1 = new Coordinate<>(123.5, 30.0);
        System.out.println(c1);
        
        Coordinate<String> c2 = new Coordinate<>("123 east longitude.5°", "30 n°");
        System.out.println(c2);
    }
}
class Coordinate<T>{
    private T x;
    private T y;
    public Coordinate(T x, T y) {
        super();
        this.x = x;
        this.y = y;
    }
    public Coordinate() {
        super();
    }
    public T getX() {
        return x;
    }
    public void setX(T x) {
        this.x = x;
    }
    public T getY() {
        return y;
    }
    public void setY(T y) {
        this.y = y;
    }
    @Override
    public String toString() {
        return "Coordinate [x=" + x + ", y=" + y + "]";
    }
    
}

Question 3

Case:

1. Declare a generic method that can exchange elements at a specified location in any reference type array.

public static <T> void method( T[] arr,int a,int b)

2. Call test in main method.

package com.atguigu.test03;
​
public class Test03 {
    public static void main(String[] args) {
        Integer[] arr = {1,2,3,4,5,6};
        method(arr,0,1);
        for (Integer num : arr) {
            System.out.println(num);
        }
    }
    public static <T> void method( T[] arr,int a,int b){
         //Element exchange
        T temp = arr[a];
        arr[a] = arr[b];
        arr[b] = temp;
    }
}
​

Question 4

Case:

1. Declare a generic method that can receive an array of any reference type and invert all elements in the array

public static <T> void reverse(T[] arr)

2. Call test in main method.

package com.atguigu.test04;
​
import java.util.Arrays;
​
public class Test04 {
    public static void main(String[] args) {
        Integer[] arr = {1,2,3,4,5,6};
        reverse(arr);
        System.out.println(Arrays.toString(arr));
    }
    public static <T> void reverse(T[] arr){
        for (int i = 0; i < arr.length/2; i++) {
            T temp = arr[i];
            arr[i] = arr[arr.length-1-i];
            arr[arr.length-1-i] = temp;
        }
    }
}
​

Question 5

Case:

1. Declare a generic method, which can sort any object array from small to large according to the natural sorting of elements, and implement it with bubble sorting

public static <T> void sort(T[] arr)

2. Declare a generic method, which can sort any object array from small to large according to the specified comparator, and implement it with bubble sorting

public static <T> void sort(T[] arr, Comparator<? super T> c)

package com.atguigu.test05;
​
import java.util.Arrays;
import java.util.Comparator;
​
public class Test05 {
    public static void main(String[] args) {
        Integer[] arr = {2,4,7,1,3};
        sort(arr);
        System.out.println(Arrays.toString(arr));
        
        String[] all = {"hello","Hello","Chai","chai"};
        sort(all,new Comparator<String>() {
​
            @Override
            public int compare(String o1, String o2) {
                return o1.compareToIgnoreCase(o2);
            }
        });
        System.out.println(Arrays.toString(all));
    }
    public static <T extends Comparable<T>> void sort(T[] arr){
        for (int i = 1; i < arr.length; i++) {
            for (int j = 0; j < arr.length-i; j++) {
                if(arr[j].compareTo(arr[j+1])>0){
                    T temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
            }
        }
    }
    public static <T> void sort(T[] arr, Comparator<? super T> c){
        for (int i = 1; i < arr.length; i++) {
            for (int j = 0; j < arr.length-i; j++) {
                if(c.compare(arr[j], arr[j+1])>0){
                    T temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
            }
        }
    }
}
​

Set exercises

Question 1

  • Random verification code.

    • A verification code composed of ten groups of six characters is randomly generated.

    • The verification code consists of upper and lower case letters and numeric characters.

  • Code implementation, and the effect is shown in the figure:

  • Development tips:

    • Use the character array to save the original characters, and use the Random class to generate a Random index.

    • Put ten sets of verification codes into the collection

    • Traversing a collection with an Iterator iterator

package com.atguigu.test01;
​
import java.util.Collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
​
public class Test01 {
    @SuppressWarnings("all")
    public static void main(String[] args) {
        char[] arr = new char[26+26+10];
        
        //Use a character array to save the original characters
        for (int i = 0; i < arr.length; i++) {
            if(i<10){//First 10 digits
                arr[i] = (char)(i+48);
            }else if(i<10+26){//26 capital letters in the middle
                arr[i] = (char)(i+65-10);
            }else{//Put the rest in lowercase letters
                arr[i] = (char)(i+97-10-26);
            }
        }
        
        //Randomly generate 10 groups of verification codes
        Collection<String> list = new ArrayList<String>();
        Random rand = new Random();
        for (int i = 0; i < 10; i++) {
            String str = "";
            for (int j = 0; j < 6; j++) {
                int index = rand.nextInt(arr.length);
                str += arr[index];
            }
            list.add(str);
        }
        
        Iterator<String> iter = list.iterator();
        while(iter.hasNext()){
            System.out.println("Random verification code:" + iter.next());
        }
    }
}
​

Question 2

  • Enter student information on the keyboard and save it to the collection.

    • Circular entry method: 1: continue entry, 0: end entry.

    • Define the student class. The attributes are name and age. Use the student object to save the entered data.

    • Use the ArrayList set to save the student object. After entering, use foreach to traverse the set.

  • Code implementation, and the effect is shown in the figure:

package com.atguigu.test02;
​
import java.util.Collection;
import java.util.ArrayList;
import java.util.Scanner;
​
public class Test02 {
    public static void main(String[] args) {
        Collection<Student> list = new ArrayList<Student>();
        
        Scanner input = new Scanner(System.in);
        while(true){
            System.out.print("Select (1. Enter; 0. Exit):");
            int select = input.nextInt();
            if(select == 0){
                break;
            }
            System.out.print("full name:");
            String name = input.next();
            System.out.print("Age:");
            int age = input.nextInt();
            
            Student stu = new Student(name,age);
            list.add(stu);
        }
        
        for (Student stu : list) {
            System.out.println(stu);
        }
    }
}
class Student{
    private String name;
    private int age;
    public Student(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    public Student() {
        super();
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + "]";
    }
    
}

Chapter 17

Question 1

Case:

1. Save points with a String [] array

2. Save decors with a String [] array

3. Use a String [] array to save Wang and Wang

4. Use the above array to generate a deck of playing cards

5. Traverse to display the full deck of playing cards

6. Simulate the random licensing of 4 people, each with 11 cards

7. Show everyone's cards and the remaining cards

The effects are as follows:

package com.atguigu.test01;
​
import java.util.ArrayList;
import java.util.Random;
​
public class Test01 {
    public static void main(String[] args) {
        String[] dian = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
        String[] hua = {"spade","heart","Square slice","Plum blossom"};
        String[] wang = {"king","Xiao Wang"};
        
        ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < dian.length; i++) {
            for (int j = 0; j < hua.length; j++) {
                list.add(hua[j]+dian[i]);
            }
        }
        for (int i = 0; i < wang.length; i++) {
            list.add(wang[i]);
        }
        
        for (int i = 0; i < list.size(); i++) {
            System.out.print(list.get(i)+"  ");
            if((i+1)%10==0){
                System.out.println();
            }
        }
        System.out.println();
        System.out.println("Licensing:");
        
        Random rand = new Random();
        ArrayList<String> one = new ArrayList<String>();
        for (int i = 0; i < 11; i++) {
            one.add(list.remove(rand.nextInt(list.size())));
        }
        
        ArrayList<String> two = new ArrayList<String>();
        for (int i = 0; i < 11; i++) {
            two.add(list.remove(rand.nextInt(list.size())));
        }
        
        ArrayList<String> three = new ArrayList<String>();
        for (int i = 0; i < 11; i++) {
            three.add(list.remove(rand.nextInt(list.size())));
        }
        
        ArrayList<String> four = new ArrayList<String>();
        for (int i = 0; i < 11; i++) {
            four.add(list.remove(rand.nextInt(list.size())));
        }
        
        System.out.println("First person:" + one);
        System.out.println("2nd person:" + two);
        System.out.println("The third person:" + three);
        System.out.println("The fourth person:" + four);
        System.out.println("surplus:" + list);
    }
}
​

Question 2

  • Analog lottery number.

    • Randomly generate 10 numbers into the set, ranging from 1 to 50, as lotto numbers. Cannot repeat.

    • Enter 10 integers into the set, ranging from 1 to 50, and cannot be repeated.

    • The entered integer is compared with the Lotto number, and several guesses are counted.

  • Code implementation, and the effect is shown in the figure:

Development tips:

  • When using a collection, you can use the contains method to determine whether a collection contains an element

package com.atguigu.test02;
​
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
​
public class Test02 {
    public static void main(String[] args) {
        ArrayList<Integer> lotNumList = lotNum();
        System.out.println("Lotto number has been generated,The game begins:");
        ArrayList<Integer> inputList = inputNum();
        System.out.println("The number you entered is:"+inputList);
        int count  =  countNum(inputList , lotNumList);
        System.out.println("Lotto number is:"+lotNumList);
        System.out.println("You guessed right:"+count+"Number");
    }
​
    public static int countNum(ArrayList<Integer> inputList, ArrayList<Integer> lotNumList) {
        int  count  = 0;
        for (int i = 0; i < inputList.size(); i++) {
            Object num  = inputList.get(i);
            if (lotNumList.contains(num)){
                count++;
            }
        }
        return count ;
    }
    
    public static ArrayList<Integer> inputNum(){
        ArrayList<Integer> list = new ArrayList<Integer>();
        Scanner sc = new Scanner(System.in);
        for (int i = 0; i < 10; ) {
            System.out.println("Please enter page"+(i+1)+"Number[1-50]:");
            int num  = sc.nextInt();
​
            if (num >=1 && num<=50 && !list.contains(num)){
                list.add(num);
                i++;
            }else{
                System.out.println(num+"exceed[1-50]Range or repeated entry, the number is invalid, please re-enter");
            }
        }
        sc.close();
        return list;
    }
    
    public static ArrayList<Integer> lotNum(){
        ArrayList<Integer> list = new ArrayList<Integer>();
        Random r = new Random();
        for (int i = 0; i < 10; ) {
            int num  = r.nextInt(50) + 1;
​
            if (!list.contains(num)){
                list.add(num);
                i++;
            }
        }
        return list;
    }
}

Question 3

Case:

1. Randomly generate 10 integers between [1100], put them into the List set, and traverse the display

2. Find out the top 3 maximum values and delete them. Note that they may be repeated

3. Displays the results after deletion

The effects are as follows:

package com.atguigu.test03;
​
import java.util.ArrayList;
import java.util.Random;
​
public class Test03 {
    public static void main(String[] args) {
        ArrayList<Integer> nums = getNum();
        System.out.println("10 Random values:" + nums);
        
        ArrayList<Integer> maxList = getTop3(nums);
        System.out.println("Top 3 largest:" + maxList);
        
        System.out.println("After deletion:" + nums);
    }
​
    public static ArrayList<Integer> getNum() {
        ArrayList<Integer> list = new ArrayList<Integer>();
        Random r = new Random();
        for (int i = 0; i < 10; i++) {
            int n = r.nextInt(100) + 1;
            list.add(n);
        }
        return list;
    }
    
    public static ArrayList<Integer> getTop3(ArrayList<Integer> list){
        ArrayList<Integer> maxList = new ArrayList<Integer>();
        for (int i = 0; i < 3; i++) {
            Integer max = (Integer) list.get(0);
            for (int j = 0; j < list.size(); j++) {
                Integer num = (Integer) list.get(j);
                if(max < num){
                    max = num;
                }
                
            }
            maxList.add(max);
            
            while(list.contains(max)){
                list.remove(max);
            }
        }
        
        return maxList;
    }
    
}
​

Question 4

  • Randomly generate 30 numbers, ranging from 2 to 100, and obtain the prime number.

  • Code implementation, and the effect is shown in the figure:

Development tips:

  • Prime number: a number in an integer greater than 1 that cannot be divided by other natural numbers except 1 and the integer itself.

package com.atguigu.test04;
​
import java.util.ArrayList;
import java.util.Random;
​
public class Test04 {
    public static void main(String[] args) {
        ArrayList<Integer> ranNum = getRanNum();
        System.out.println("The random number is:");
        System.out.println(ranNum);
        System.out.println("The prime number is:");
        ArrayList<Integer> pNum = getPNum(ranNum);
        System.out.println(pNum);
    }
​
    public static ArrayList<Integer> getPNum(ArrayList<Integer> ranNum) {
        ArrayList<Integer> list = new ArrayList<Integer>();
​
        for (int i = 0; i < ranNum.size(); i++) {
            Integer integer = (Integer) ranNum.get(i);
            if (isP(integer)) {
                list.add(integer);
            }
        }
        return list;
    }
​
    public static ArrayList<Integer> getRanNum() {
        Random random = new Random();
        ArrayList<Integer> list = new ArrayList<Integer>();
        for (int i = 0; i < 30; i++) {
            list.add(random.nextInt(99) + 2);
        }
        return list;
    }
​
    public static boolean isP(int n) {
        boolean isPrime = true;
        for (int i = 2; i < n; i++) {
            if (n % i == 0) {
                isPrime = false;
                break;
            }
        }
        return isPrime;
    }
}
​

Question 5

Case:

1. Please define the method public static int listTest(Collection list,String s) to count the number of occurrences of the specified element in the collection

2. Create a set that stores 30 randomly generated lowercase letters

3. Use listTest to count the number of occurrences of some elements

4. The effect is as follows

package com.atguigu.test05;
​
import java.util.ArrayList;
import java.util.Collection;
import java.util.Random;
​
public class Test05 {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        Random rand = new Random();
        for (int i = 0; i < 30; i++) {
            list.add((char)(rand.nextInt(26)+97)+"");
        }
        System.out.println(list);
        System.out.println("a:"+listTest(list, "a"));   
        System.out.println("b:"+listTest(list, "b"));   
        System.out.println("c:"+listTest(list, "c"));
        System.out.println("x:"+listTest(list, "x"));   
    }
​
    public static int listTest(Collection<String> list, String string) {
        int count = 0;
        for (String object : list) {
            if(string.equals(object)){
                count++;
            }
        }
        return count;
    }
}
​

Question 6

Case: input a string on the keyboard, remove the repeated characters, and print out different characters. The order must be guaranteed. For example, enter: aaaabbbcccddd, and the print result is: abcd. The effect is shown in the figure:

Tip: use of LinkedHashSet

package com.atguigu.test06;
​
import java.util.LinkedHashSet;
import java.util.Scanner;
​
public class Test06 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        
        System.out.print("Please enter a string of letters:");
        String str = input.nextLine();
        System.out.println("str=" + str);
        
        LinkedHashSet<Character> set = new LinkedHashSet<Character>();
        for (int i = 0; i < str.length(); i++) {
            set.add(str.charAt(i));
        }
        
        System.out.print("After weight removal:");
        String result = "";
        for (Character object : set) {
            result += object;
        }
        System.out.println(result);
    }
}
​

Question 7

Case: two color ball rule: each betting number of two-color ball consists of 6 red ball numbers and 1 blue ball number. The red ball number is selected from 1-33; The blue ball number is selected from 1-16; Please randomly generate a two-color ball number. (the same color number shall not be repeated)

Development tips: TreeSet and ArrayList can be used together

package com.atguigu.test07;
​
import java.util.ArrayList;
import java.util.Random;
import java.util.TreeSet;
​
public class Test07 {
    public static void main(String[] args) {
        TreeSet<Integer> red = new TreeSet<Integer>();
        Random rand = new Random();
        while(red.size()<6){
            red.add(rand.nextInt(33)+1);
        }
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.addAll(red);
        list.add(rand.nextInt(16)+1);//Blue number
        System.out.println("Two color ball all numbers:" + list);
        
        System.out.print("Red number:");
        for (int i = 0; i < list.size()-1; i++) {
            System.out.print(list.get(i)+" ");
        }
        System.out.println("Blue number:" + list.get(list.size()-1));
    }
}
​

Question 8

Case: there are four students' scores as follows:

(1) Use the Comparable interface to sort the scores of the following four students in descending order. If the scores are the same, sort them according to their age on the basis of score sorting.

(2) Sorting by name with Comparator

(3) The effect is as follows

package com.atguigu.test08;
​
import java.util.Comparator;
import java.util.TreeSet;
​
public class Test08 {
    public static void main(String[] args) {
        System.out.println("Sort by grades and age:");
        TreeSet<Student> set = new TreeSet<Student>();
        set.add(new Student("liusan",20,90.0));
        set.add(new Student("lisi",22,90.0));
        set.add(new Student("wangwu",20,99.0));
        set.add(new Student("sunliu",22,100.0));
        for (Object object : set) {
            System.out.println(object);
        }
        
        System.out.println("Sort by name:");
        TreeSet<Student> all = new TreeSet<Student>(new Comparator<Student>() {
​
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        for (Student object : set) {
            all.add(object);
        }
        for (Student object : all) {
            System.out.println(object);
        }
    }
}
class Student implements Comparable<Student>{
    private String name;
    private int age;
    private double score;
    public Student(String name, int age, double score) {
        super();
        this.name = name;
        this.age = age;
        this.score = score;
    }
    public Student() {
        super();
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public double getScore() {
        return score;
    }
    public void setScore(double score) {
        this.score = score;
    }
    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + ", score=" + score + "]";
    }
    @Override
    public int compareTo(Student o) {
        if(this.getScore()>o.getScore()){
            return -1;
        }else if(this.getScore() < o.getScore()){
            return 1;
        }
        return this.getAge() - o.getAge();
    }
    
}

Chapter 18

Question 1

Development tips: you can use Map. key is the letter and value is the number of times of the letter

Effect demonstration: for example: String str = "Your future depends on your dreams, so go to sleep.";

package com.atguigu.test01;
​
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
​
public class Test01 {
    public static void main(String[] args) {
        String str = "Your future depends on your dreams, so go to sleep.";
        str = str.replaceAll("[^a-zA-Z]", "");
        HashMap<Character,Integer> map = new HashMap<Character,Integer>();
        char[] arr = str.toCharArray();
        for (int i = 0; i < arr.length; i++) {
            if(map.containsKey(arr[i])){
                Integer count = map.get(arr[i]);
                map.put(arr[i], count+1);
            }else{
                map.put(arr[i], 1);
            }
        }
        
        Set<Entry<Character,Integer>> entrySet = map.entrySet();
        for (Entry<Character,Integer> object : entrySet) {
            System.out.println(object);
        }
    }
}
​

Question 2

Case: add the singer you like and the songs you like he has sung

For example:

package com.atguigu.test02;
​
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
​
public class Test02 {
    public static void main(String[] args) {
        HashMap<String,ArrayList<String>> map = new HashMap<>();
        
        ArrayList<String> wangfei = new ArrayList<String>();
        wangfei.add("<Red beans");
        wangfei.add("<Legend");
        wangfei.add("<Vulnerable women");
        map.put("Faye Wong", wangfei);
        
        
        ArrayList<String> zxy = new ArrayList<String>();
        zxy.add("<Have you along the way");
        zxy.add("<Kiss goodbye");
        zxy.add("<A thousand sad reasons");
        map.put("Xue You Zhang", zxy);
        
        Set<Entry<String, ArrayList<String>>> entrySet = map.entrySet();
        for (Entry<String, ArrayList<String>> object : entrySet) {
            System.out.println(object);
        }
    }
}
​

Question 3

Case:

Add the following province and city information to the map and traverse the display

Zhejiang Province
    Shaoxing City
    Wenzhou City
    Huzhou City
    Jiaxing City
    Taizhou City
    Jinhua City
    Zhoushan City
    Quzhou City
    Lishui City
    Hangzhou
    Ningbo City
 Hainan 
    Haikou City
    The city of Sanya
 Beijing
    Beijing

Development tips:

Where key is the name of the province and value is all the municipal districts of the province

package com.atguigu.test03;
​
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
​
public class Test03 {
    public static void main(String[] args) throws Exception {
        HashMap<String,List<String>> map = new HashMap<>();
        map.put("Beijing", Arrays.asList("Beijing"));
        map.put("Hainan ", Arrays.asList("Haikou City","The city of Sanya"));
        map.put("Zhejiang Province", Arrays.asList("Shaoxing City","Wenzhou City","Huzhou City","Jiaxing City","Taizhou City","Jinhua City","Zhoushan City","Quzhou City","Lishui City"));
    
        Set<Entry<String, List<String>>> entrySet = map.entrySet();
        for (Entry<String, List<String>> object : entrySet) {
            System.out.println(object);
        }
    }
}
​

Question 4

Case: code implementation of simulating landlords' shuffling and licensing and sorting cards

The operation effect is as follows:

Development tips:

(1) Use string [] num = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "a", "2"}; Store numbers

String[] colors = {"square slice", "plum blossom", "heart", "spade"}; Store decors

(2) Deal with Wang and Xiao Wang separately

(3) Store the index [1,54] numbers of 54 cards in an ArrayList in turn

(4) Use the combination of nums and colors array to store 54 cards in a Map. key is the index, the range is 1-54, and value is the card face. For example: (1, spade 3) (54, Xiao Wang)

(5) Shuffle the ArrayList and disrupt the order

(6) Take the index in the list in turn and send it to four card friends. The cards of four card friends can be stored in TreeSet, which can be sorted according to the index size. The index size is the size of the cards

(7) As a result of traversal, the index of cards is stored in TreeSet, and the cards are taken from the Map for display

package com.atguigu.test04;
​
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.TreeSet;
​
public class Test04 {
​
    public static void main(String[] args) {
        String[] nums = { "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2" };
        String[] colors = { "Square slice", "Plum blossom", "heart", "spade" };
        
        ArrayList<Integer> list = new ArrayList<Integer>(); // Store the index of Chapter 54 [0,53]
        HashMap<Integer,String> map = new HashMap<>(); // Store index and playing cards
        int index = 1; // Start value of index
        for (String num : nums) {
            for (String color : colors) {
                map.put(index, color.concat(num)); // Add index and playing cards to HashMap
                list.add(index); // Adds an index to the ArrayList collection
                index++;
            }
        }
        map.put(index, "Xiao Wang");
        list.add(index);
        index++;
        map.put(index, "king");
        list.add(index);
        // shuffle the cards
        Collections.shuffle(list);
        // Licensing
        TreeSet<Integer> left = new TreeSet<Integer>();
        TreeSet<Integer> right = new TreeSet<Integer>();
        TreeSet<Integer> me = new TreeSet<Integer>();
        TreeSet<Integer> up = new TreeSet<Integer>();
        TreeSet<Integer> lastCards = new TreeSet<Integer>();
        for (int i = 0; i < 13; i++) {
            right.add(list.remove(0));
            left.add(list.remove(0));
            me.add(list.remove(0));
            up.add(list.remove(0));
        }
        lastCards.addAll(list);
​
        // Look at the cards
        lookPoker("Left player", left, map);
        lookPoker("Right player", right, map);
        lookPoker("Upper player", up, map);
        lookPoker("I", me, map);
        lookPoker("a hand", lastCards, map);
}
​
    public static void lookPoker(String name, TreeSet<Integer> ts, HashMap<Integer, String> map) {
        System.out.println(name + "Your card is:");
        for (Integer index : ts) {
            System.out.print(map.get(index) + " ");
        }
​
        System.out.println();
    }
}
​

Question 5

Case:

(1) Input a year from the keyboard and output which team is the world cup champion in that year. If no world cup is held in that year, output: no world cup is held.

(2) Input the name of a team from the keyboard and output the list of years in which the team won the championship. For example, if you read "Brazil", you should output 1958, 1962, 1970, 1994, 2002, read "Netherlands", and you should output that you have not won the world cup

The operation effect is as follows:

Development tips:

Take the year as the key, and save the name of the country that won the championship in the new year as the value in the map

Attachment: previous World Cup Champions

Number of sessionsYear of holdingVenuechampion
First session1930UruguayUruguay
Second session1934ItalyItaly
Third session1938FranceItaly
Fourth session1950BrazilUruguay
Fifth session1954SwitzerlandWest Germany
Sixth session1958SwedenBrazil
Seventh session1962ChileBrazil
Eighth session1966EnglandEngland
Ninth session1970MexicoBrazil
Tenth session1974Former West GermanyWest Germany
Eleventh session1978ArgentinaArgentina
Twelfth1982SpainItaly
Thirteenth session1986MexicoArgentina
14th session1990ItalyWest Germany
15th1994U.S.ABrazil
Sixteenth session1998FranceFrance
Seventeenth session2002Korea and JapanBrazil
18th session2006GermanyItaly
Nineteenth session2010South AfricaSpain
Twentieth session2014BrazilGermany
Twenty first session2018RussiaFrance
package com.atguigu.test05;
​
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
​
public class Test05 {
    public static void main(String[] args) {
​
        Map<Integer,String> m = new HashMap<>();
​
        m.put(1930, "Uruguay");
        m.put(1934, "Italy");
        m.put(1938, "Italy");
        m.put(1950, "Uruguay");
        m.put(1954, "West Germany");
        m.put(1958, "Brazil");
        m.put(1962, "Brazil");
        m.put(1966, "England");
        m.put(1970, "Brazil");
        m.put(1974, "West Germany");
        m.put(1978, "Argentina");
        m.put(1982, "Italy");
        m.put(1986, "Argentina");
        m.put(1990, "West Germany");
        m.put(1994, "Brazil");
        m.put(1998, "France");
        m.put(2002, "Brazil");
        m.put(2006, "Italy");
        m.put(2010, "Spain");
        m.put(2014, "Germany");
        m.put(2018, "France");
​
        Scanner input = new Scanner(System.in);
        System.out.print("Please enter a year:");
        int key = input.nextInt();
​
        if (m.containsKey(key)) {
            System.out.println(key + "In, the World Cup winners were:" + m.get(key));
        } else {
            System.out.println("There was no world cup that year!");
        }
​
        System.out.print("Please enter a country name:");
        String country = input.next();
​
        if (m.containsValue(country)) {
            System.out.println("The national team has won the championship in the following years:");
            for (Integer year : m.keySet()) {
                if (m.get(year).equals(country)) {
                    System.out.println(year);
                }
            }
        } else {
            System.out.println("The country did not win the world cup");
        }
​
    }
}
​

Question 6

Case: simulate the secondary linkage effect of the menu

The existing information strings of provinces and cities in China are as follows:

        String str = "'Beijing': ['Beijing'];"
                +"'Shanghai': ['Shanghai'];"
                +"'Tianjin': ['Tianjin'];"
                +"'Chongqing': ['Chongqing'];"
                +"'Hebei Province': ['Shijiazhuang', 'Zhangjiakou', 'Chengde', 'qinghuangdao', 'Tangshan', 'Langfang', 'Baoding', 'Cangzhou', 'Hengshui', 'Xingtai', 'Handan'];"
                +"'Shanxi Province': ['Taiyuan', 'da tong', 'Shuozhou', 'Yangquan', 'CiH ', 'Jincheng', 'Xinzhou', 'Lv Liang', 'Jinzhong', 'Linfen', 'Yuncheng'];"
                +"'Liaoning Province': ['Shenyang', 'Sunrise', 'Fuxin', 'Tieling', 'Fushun', 'Benxi', 'Liaoyang', 'Anshan', 'Dandong', 'Dalian', 'Yingkou', 'Panjin', 'Jinzhou', 'Huludao'];"
                +"'Jilin Province': ['Changchun', 'Baicheng', 'Songyuan', 'Jilin', 'Siping', 'Liaoyuan', 'make well-connected', 'mount bai', 'Yanbian'];"
                +"'Heilongjiang Province': ['Harbin', 'Qiqihar', 'Heihe River', 'Daqing', 'Yichun', 'Hegang', 'Jiamusi', 'Shuangyashan', 'Qitaihe', 'Jixi', 'Mudanjiang', 'Suihua', 'Daxing'an'];"
                +"'Jiangsu Province': ['Nanjing', 'Xuzhou', 'Lianyungang', 'Suqian', 'Huaiyin', 'ynz ', 'Yangzhou', 'Taizhou', 'Nantong', 'Zhenjiang', 'Changzhou', 'Wuxi', 'Suzhou'];"
                +"'Zhejiang Province': ['Hangzhou', 'Huzhou', 'Jiaxing', 'Zhoushan', 'Ningbo', 'Shaoxing', 'Jinhua', 'Taizhou', 'Wenzhou', 'Lishui','Quzhou'];"
                +"'Anhui Province': ['Hefei', 'Suzhou', 'Huaibei', 'Fuyang', 'Bengbu', 'Huainan', 'Chuzhou', 'Ma On Shan', 'Wuhu', 'Tongling', 'Anqing', 'Mount Huangshan', 'Lu'an', 'Chaohu Lake', 'Chizhou', 'Xuancheng'];"
                +"'Fujian Province': ['Fuzhou', 'Nanping', 'Sanming', 'Putian', 'Quanzhou', 'Xiamen', 'Zhangzhou', 'Longyan', 'Ningde'];"
                +"'Jiangxi Province': ['Nanchang', 'Jiujiang', 'Jingdezhen', 'Yingtan', 'Xinyu', 'Pingxiang', 'Ganzhou', 'Shangrao', 'Fuzhou', 'Yichun', 'Ji'an'];"
                +"'Shandong Province': ['Jinan', 'Liaocheng', 'Texas', 'doy ', 'Zibo', 'Weifang', 'Yantai', 'Weihai', 'Qingdao', 'sunshine', 'Linyi', 'Zaozhuang', 'Jining', 'Taian', 'Laiwu prefecture level city in Shandong', 'Binzhou', 'Heze'];"
                +"'Henan Province': ['Zhengzhou', 'Sanmenxia', 'Luoyang', 'Jiaozuo', 'Xinxiang', 'Hebi', 'Anyang', 'Puyang', 'Kaifeng', 'Shangqiu', 'Xu Chang', 'Luohe', 'Pingdingshan', 'Nanyang', 'Xinyang', 'Zhoukou', 'Zhumadian'];"
                +"'Hubei province': ['Wuhan', 'Shiyan', 'Xiangpan', 'Jingmen', 'Filial piety', 'Huanggang', 'Ezhou', 'Yellowstone', 'Xianning', 'Jingzhou', 'Yichang', 'Enshi', 'Xiangfan'];"
                +"'Hunan Province': ['Changsha', 'Zhangjiajie', 'Changde', 'Yiyang', 'Yueyang', 'Zhuzhou', 'Xiangtan', 'city in Hunan', 'Chenzhou', 'Yongzhou', 'Shaoyang', 'Huaihua', 'Loudi', 'Xiangxi'];"
                +"'Guangdong Province': ['Guangzhou', 'Qingyuan', 'Shaoguan', 'Heyuan', 'Meizhou', 'Chaozhou', 'Shantou', 'Jieyang', 'Shanwei', 'Huizhou', 'Dongguan', 'Shenzhen', 'Zhuhai', 'Jiangmen', 'Foshan', 'Zhaoqing', 'Yunfu', 'Yangjiang', 'Maoming', 'Zhanjiang'];"
                +"'Hainan ': ['Haikou', 'Sanya'];"
                +"'Sichuan Province': ['Chengdu', 'Guangyuan', 'Mianyang', 'Deyang', 'Nao ', 'Guang'an', 'Suining', 'Neijiang', 'Leshan', 'Zigong', 'Luzhou', 'Yibin', 'Panzhihua', 'Bazhong', 'Dachuan', 'Ziyang', 'Meishan', 'Ya'an', 'ABA', 'Ganzi', 'Liangshan'];"
                +"'Guizhou Province': ['Guiyang', 'Liupanshui', 'Zunyi', 'Bijie', 'Tongren', 'Anshun', 'Southeast Guizhou', 'Qiannan', 'Southwest Guizhou'];"
                +"'Yunnan Province': ['Kunming', 'Qu Jing', 'Yuxi', 'Lijiang', 'Zhaotong', 'Simao', 'Lincang', 'Baoshan', 'Dehong', 'Nujiang River', 'Diqing', 'Dali', 'Chu Xiong', 'Red River', 'Wenshan', 'Xishuangbanna'];"
                +"'Shaanxi Province': ['Xi'an', 'Yan'an', 'Tongchuan', 'Weinan', 'Xianyang', 'Baoji', 'Hanzhong', 'Yulin', 'Shangluo', 'Ankang'];"
                +"'Gansu Province': ['Lanzhou', 'Jiayuguan', 'Jinchang', 'silver', 'Tianshui', 'Jiuquan', 'Zhangye', 'Wuwei', 'Qingyang', 'Pingliang', 'Dingxi', 'Longnan', 'Linxia', 'Gannan'];"
                +"'Qinghai Province': ['Xining', 'Haidong', 'Xining', 'Haibei', 'Hainan', 'Huang Nan', 'GOLO', 'Yushu', 'Haixi'];"
                +"'Inner Mongolia': ['Hohhot', 'Baotou', 'Wuhai', 'Chifeng', 'Hulunbuir League', 'Xing'an League', 'Zhelimu League', 'Xilin Gol League', 'Ulanqab League', 'erdos', 'Bayannur League', 'alxa league '];"
                +"'Guangxi': ['Nanning', 'Guilin', 'city in Guangxi', 'Wuzhou', 'Guigang', 'Yulin', 'Qinzhou', 'the north sea', 'port of fangcheng', 'Nanning', 'Baise', 'Hechi', 'city in Guangxi', 'Hezhou'];"
                +"'Tibet': ['Lhasa', 'Naqu', 'Qamdo', 'Nyingchi', 'Shannan', 'Shigatse', 'Ali'];"
                +"'Ningxia': ['Yinchuan', 'Shizuishan', 'Wu Zhong', 'Guyuan'];"
                +"'Xinjiang': ['Urumqi', 'Karamay', 'Kashgar', 'Aksu', 'Hotan', 'Turpan', 'Hami', 'Bortara', 'Changji', 'Bayingolin', 'Ili ', 'Tuscaloosa ', 'Altay'];"
                +"'Hong Kong': ['Hong Kong'];"
                +"'Macao': ['Macao'];"
                +"'Taiwan': ['Taipei', 'Tainan', 'other']";

The effects are as follows:

Please select:
1:Beijing
2:Shanghai
3:Tianjin
4:Chongqing
5:Hebei Province
6:Shanxi Province
7:Liaoning Province
8:Jilin Province
9:Heilongjiang Province
10:Jiangsu Province
11:Zhejiang Province
12:Anhui Province
13:Fujian Province
14:Jiangxi Province
15:Shandong Province
16:Henan Province
17:Hubei province
18:Hunan Province
19:Guangdong Province
20:Hainan 
21:Sichuan Province
22:Guizhou Province
23:Yunnan Province
24:Shaanxi Province
25:Gansu Province
26:Qinghai Province
27:Inner Mongolia
28:Guangxi
29:Tibet
30:Ningxia
31:Xinjiang
32:Hong Kong
33:Macao
34:Taiwan
 Province: 11
 The province has jurisdiction:[Hangzhou, Huzhou, Jiaxing, Zhoushan, Ningbo, Shaoxing, Jinhua, Taizhou, Wenzhou, Lishui, Quzhou]

Development tips:

(1) Put the string str first according to; After splitting, 34 provinces (including 23 provinces, 5 autonomous regions, 4 municipalities directly under the central government and 2 special administrative regions) are obtained. In the following title description, they are all provinces)

(2) Then, split the string of each province according to: so: the name of the province on the left and the municipal districts of the province on the right

(3) Store 34 provinces in a HashMap set, where the number is key and the province name is value

(4) Store the cities of all provinces in a LinkedHashMap set, where the province name is key, and all cities of the province are loaded with an ArrayList set and then used as value.

(5) Note: during string processing, pay attention to the processing of punctuation marks such as: [,],,, '

For example:

Remove single quotes'
replace("'", "")

Remove[,],',Space
replaceAll("\\[|\\]|\\'| ", "")
package com.atguigu.test06;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;

public class Test06 {
	public static void main(String[] args) {
		LinkedHashMap<String,ArrayList<String>> all = new LinkedHashMap<>();
		HashMap<Integer,String> allProvinces = new HashMap<>();
		String str = "'Beijing': ['Beijing'];"
				+"'Shanghai': ['Shanghai'];"
				+"'Tianjin': ['Tianjin'];"
				+"'Chongqing': ['Chongqing'];"
				+"'Hebei Province': ['Shijiazhuang', 'Zhangjiakou', 'Chengde', 'qinghuangdao', 'Tangshan', 'Langfang', 'Baoding', 'Cangzhou', 'Hengshui', 'Xingtai', 'Handan'];"
				+"'Shanxi Province': ['Taiyuan', 'da tong', 'Shuozhou', 'Yangquan', 'CiH ', 'Jincheng', 'Xinzhou', 'Lv Liang', 'Jinzhong', 'Linfen', 'Yuncheng'];"
				+"'Liaoning Province': ['Shenyang', 'Sunrise', 'Fuxin', 'Tieling', 'Fushun', 'Benxi', 'Liaoyang', 'Anshan', 'Dandong', 'Dalian', 'Yingkou', 'Panjin', 'Jinzhou', 'Huludao'];"
				+"'Jilin Province': ['Changchun', 'Baicheng', 'Songyuan', 'Jilin', 'Siping', 'Liaoyuan', 'make well-connected', 'mount bai', 'Yanbian'];"
				+"'Heilongjiang Province': ['Harbin', 'Qiqihar', 'Heihe River', 'Daqing', 'Yichun', 'Hegang', 'Jiamusi', 'Shuangyashan', 'Qitaihe', 'Jixi', 'Mudanjiang', 'Suihua', 'Daxing'an'];"
				+"'Jiangsu Province': ['Nanjing', 'Xuzhou', 'Lianyungang', 'Suqian', 'Huaiyin', 'ynz ', 'Yangzhou', 'Taizhou', 'Nantong', 'Zhenjiang', 'Changzhou', 'Wuxi', 'Suzhou'];"
				+"'Zhejiang Province': ['Hangzhou', 'Huzhou', 'Jiaxing', 'Zhoushan', 'Ningbo', 'Shaoxing', 'Jinhua', 'Taizhou', 'Wenzhou', 'Lishui','Quzhou'];"
				+"'Anhui Province': ['Hefei', 'Suzhou', 'Huaibei', 'Fuyang', 'Bengbu', 'Huainan', 'Chuzhou', 'Ma On Shan', 'Wuhu', 'Tongling', 'Anqing', 'Mount Huangshan', 'Lu'an', 'Chaohu Lake', 'Chizhou', 'Xuancheng'];"
				+"'Fujian Province': ['Fuzhou', 'Nanping', 'Sanming', 'Putian', 'Quanzhou', 'Xiamen', 'Zhangzhou', 'Longyan', 'Ningde'];"
				+"'Jiangxi Province': ['Nanchang', 'Jiujiang', 'Jingdezhen', 'Yingtan', 'Xinyu', 'Pingxiang', 'Ganzhou', 'Shangrao', 'Fuzhou', 'Yichun', 'Ji'an'];"
				+"'Shandong Province': ['Jinan', 'Liaocheng', 'Texas', 'doy ', 'Zibo', 'Weifang', 'Yantai', 'Weihai', 'Qingdao', 'sunshine', 'Linyi', 'Zaozhuang', 'Jining', 'Taian', 'Laiwu prefecture level city in Shandong', 'Binzhou', 'Heze'];"
				+"'Henan Province': ['Zhengzhou', 'Sanmenxia', 'Luoyang', 'Jiaozuo', 'Xinxiang', 'Hebi', 'Anyang', 'Puyang', 'Kaifeng', 'Shangqiu', 'Xu Chang', 'Luohe', 'Pingdingshan', 'Nanyang', 'Xinyang', 'Zhoukou', 'Zhumadian'];"
				+"'Hubei province': ['Wuhan', 'Shiyan', 'Xiangpan', 'Jingmen', 'Filial piety', 'Huanggang', 'Ezhou', 'Yellowstone', 'Xianning', 'Jingzhou', 'Yichang', 'Enshi', 'Xiangfan'];"
				+"'Hunan Province': ['Changsha', 'Zhangjiajie', 'Changde', 'Yiyang', 'Yueyang', 'Zhuzhou', 'Xiangtan', 'city in Hunan', 'Chenzhou', 'Yongzhou', 'Shaoyang', 'Huaihua', 'Loudi', 'Xiangxi'];"
				+"'Guangdong Province': ['Guangzhou', 'Qingyuan', 'Shaoguan', 'Heyuan', 'Meizhou', 'Chaozhou', 'Shantou', 'Jieyang', 'Shanwei', 'Huizhou', 'Dongguan', 'Shenzhen', 'Zhuhai', 'Jiangmen', 'Foshan', 'Zhaoqing', 'Yunfu', 'Yangjiang', 'Maoming', 'Zhanjiang'];"
				+"'Hainan ': ['Haikou', 'Sanya'];"
				+"'Sichuan Province': ['Chengdu', 'Guangyuan', 'Mianyang', 'Deyang', 'Nao ', 'Guang'an', 'Suining', 'Neijiang', 'Leshan', 'Zigong', 'Luzhou', 'Yibin', 'Panzhihua', 'Bazhong', 'Dachuan', 'Ziyang', 'Meishan', 'Ya'an', 'ABA', 'Ganzi', 'Liangshan'];"
				+"'Guizhou Province': ['Guiyang', 'Liupanshui', 'Zunyi', 'Bijie', 'Tongren', 'Anshun', 'Southeast Guizhou', 'Qiannan', 'Southwest Guizhou'];"
				+"'Yunnan Province': ['Kunming', 'Qu Jing', 'Yuxi', 'Lijiang', 'Zhaotong', 'Simao', 'Lincang', 'Baoshan', 'Dehong', 'Nujiang River', 'Diqing', 'Dali', 'Chu Xiong', 'Red River', 'Wenshan', 'Xishuangbanna'];"
				+"'Shaanxi Province': ['Xi'an', 'Yan'an', 'Tongchuan', 'Weinan', 'Xianyang', 'Baoji', 'Hanzhong', 'Yulin', 'Shangluo', 'Ankang'];"
				+"'Gansu Province': ['Lanzhou', 'Jiayuguan', 'Jinchang', 'silver', 'Tianshui', 'Jiuquan', 'Zhangye', 'Wuwei', 'Qingyang', 'Pingliang', 'Dingxi', 'Longnan', 'Linxia', 'Gannan'];"
				+"'Qinghai Province': ['Xining', 'Haidong', 'Xining', 'Haibei', 'Hainan', 'Huang Nan', 'GOLO', 'Yushu', 'Haixi'];"
				+"'Inner Mongolia': ['Hohhot', 'Baotou', 'Wuhai', 'Chifeng', 'Hulunbuir League', 'Xing'an League', 'Zhelimu League', 'Xilin Gol League', 'Ulanqab League', 'erdos', 'Bayannur League', 'alxa league '];"
				+"'Guangxi': ['Nanning', 'Guilin', 'city in Guangxi', 'Wuzhou', 'Guigang', 'Yulin', 'Qinzhou', 'the north sea', 'port of fangcheng', 'Nanning', 'Baise', 'Hechi', 'city in Guangxi', 'Hezhou'];"
				+"'Tibet': ['Lhasa', 'Naqu', 'Qamdo', 'Nyingchi', 'Shannan', 'Shigatse', 'Ali'];"
				+"'Ningxia': ['Yinchuan', 'Shizuishan', 'Wu Zhong', 'Guyuan'];"
				+"'Xinjiang': ['Urumqi', 'Karamay', 'Kashgar', 'Aksu', 'Hotan', 'Turpan', 'Hami', 'Bortara', 'Changji', 'Bayingolin', 'Ili ', 'Tuscaloosa ', 'Altay'];"
				+"'Hong Kong': ['Hong Kong'];"
				+"'Macao': ['Macao'];"
				+"'Taiwan': ['Taipei', 'Tainan', 'other']";
		
		String[] provincesStr = str.split(";");
		for (int i = 0; i < provincesStr.length; i++) {
			String[] split = provincesStr[i].split(":");
			String proviceName = split[0].replace("'", "");
			allProvinces.put(i+1, proviceName);
			
			ArrayList<String> cityList = new ArrayList<String>();
			String[] cityStrings = split[1].replaceAll("\\[|\\]|\\'| ", "").split(",");
			for (int j = 0; j < cityStrings.length; j++) {
				cityList.add(cityStrings[j]);
			}
			all.put(proviceName, cityList);
		}
		
		Scanner input = new Scanner(System.in);
		System.out.println("Please select:");
		Set<Entry<Integer, String>> entrySet = allProvinces.entrySet();
		for (Entry<Integer, String> object : entrySet) {
			System.out.println(object); 
		}
		System.out.print("province:");
		int select = input.nextInt();
		System.out.println("The province has jurisdiction:" + all.get(allProvinces.get(select)));
	}
}

Chapter XIX

File operation

Question 1

Case:

1. Using the absolute path, create a testIO folder under disk D, and then create a 1. 0 folder in the testIO folder Txt file

2. Using the relative path, create a testIO folder under the current project, and then create a 1. 0 folder in the testIO folder Txt file

package com.atguigu.test01;
​
import java.io.File;
import java.io.IOException;
​
import org.junit.Test;
​
public class Test01 {
    @Test
    public void test01() throws IOException {
        File dir = new File("d:/testIO");
        dir.mkdir();
        
        File file = new File("d:/testIO/1.txt");
        file.createNewFile();
    }
    
    @Test
    public void test02() throws IOException {
        File dir = new File("testIO");
        dir.mkdir();
        
        File file = new File("testIO/1.txt");
        file.createNewFile();
    }
}

Question 2

Case:

1. Check whether the file a.txt exists in the testIO folder of disk D. if it does not exist, create the file.

2. Obtain the file name, file size, absolute path and parent path of the a.txt file in the testIO folder of disk D, and output the information to the console

3. Judge file = new file ("D: \ testio"); File or not, if it is a file, output: xxx is a file, if it is a folder, output: xxx is a folder

4. Delete the a.txt file in the testIO folder of disk D

5. Delete 1. 0 in the testIO folder under the current project Txt file, and then delete the testIO folder

package com.atguigu.test02;
​
import java.io.File;
import java.io.IOException;
​
import org.junit.Test;
​
public class Test02 {
    @Test
    public void test05(){
        File file = new File("d:/testIO/1.txt");
        file.delete();
        
        File dir = new File("d:/testIO");
        dir.delete();
    }
    
    @Test
    public void test04(){
        File file = new File("d:/testIO/a.txt");
        file.delete();
    }
    @Test
    public void test03(){
        File file = new File("d:/testIO");
        if(file.isFile()){
            System.out.println(file+"It's a file.");
        }else if(file.isDirectory()){
            System.out.println(file + "Is a folder");
        }
    }
    @Test
    public void test02(){
        File file = new File("d:/testIO/a.txt");
        System.out.println("File name:" + file.getName());
        System.out.println("File size:" + file.length());
        System.out.println("Absolute path to file:" + file.getAbsolutePath());
        System.out.println("Parent directory of file:" + file.getParent());
    }
    @Test
    public void test01(){
        File file = new File("d:/testIO/a.txt");
        try {
            if(!file.exists()){
                file.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }       
    }
}

IO stream operation

Question 3

Case:

1. Copy the teacher's word note document "Chapter 14 IO stream. docx" to the testIO folder of the current project.

2. Buffer stream and file stream are required to be implemented together

package com.atguigu.test03;
​
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
​
public class Test03 {
    public static void main(String[] args) {
        try(
                BufferedInputStream bis = new BufferedInputStream(
                        new FileInputStream("D:/Shang Silicon Valley_190513 class_Chai Linyan_JavaSE/note/Chapter 14 IO flow.docx"));
                BufferedOutputStream bos = new BufferedOutputStream(
                        new FileOutputStream("testIO/Chapter 14 IO flow.docx"));
        ){
            byte[] data = new byte[1024];
            int len;
            while((len = bis.read(data))!=-1){
                bos.write(data, 0, len);
            }
        }catch(IOException e){
            e.printStackTrace();
        }
    }
}

Question 4

Case:

Put today's homework folder day22_ The character code of "I want to tell you. txt" under homework is GBK, and the character code of "teacher Chai's words. txt" copied to the testIO folder of the current project is UTF-8

package com.atguigu.test04;
​
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
​
public class Test04 {
    public static void main(String[] args) {
        try(
            FileInputStream fis = new FileInputStream("d:/atguigu/day22_homework/I want to tell you.txt");
            BufferedInputStream bis = new BufferedInputStream(fis);
            InputStreamReader isr = new InputStreamReader(bis,"GBK");
                
            FileOutputStream fos = new FileOutputStream("testIO/Teacher Chai's words.txt");
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            OutputStreamWriter osw = new OutputStreamWriter(bos, "UTF-8");  
        ){
            char[] data = new char[1024];
            int len;
            while((len = isr.read(data))!=-1){
                osw.write(data, 0, len);
            }
        }catch(IOException e){
            e.printStackTrace();
        }
    }
}
​

Question 5

Case:

Store the following data in a data Dat file, and read the display again

int a = 10;
char c = 'a';
double d = 2.5;
boolean b = true;
String str = "Shang Silicon Valley";
package com.atguigu.test05;
​
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
​
import org.junit.Test;
​
public class Test05 {
    @Test
    public void test02() throws IOException {
        DataInputStream dis = new DataInputStream(new FileInputStream("data.dat"));
        System.out.println(dis.readInt());
        System.out.println(dis.readChar());
        System.out.println(dis.readDouble());
        System.out.println(dis.readBoolean());
        System.out.println(dis.readUTF());
        dis.close();
    }
    
    @Test
    public void test01() throws IOException {
        int a = 10;
        char c = 'a';
        double d = 2.5;
        boolean b = true;
        String str = "Shang Silicon Valley";
        
        DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.dat"));
        dos.writeInt(a);
        dos.writeChar(c);
        dos.writeDouble(d);
        dos.writeBoolean(b);
        dos.writeUTF(str);
        dos.close();
    }
}

Question 6

Case:

1. Declare a Message class, including sender, receiver, Message content and sending time

2. Create a Message object and write it to Message Dat file and read the display again

package com.atguigu.test06;
​
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
​
import org.junit.Test;
​
public class Test06 {
    @Test
    public void test02() throws FileNotFoundException, IOException, ClassNotFoundException{
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("message.dat"));
        Object msg = ois.readObject();
        System.out.println(msg);
        ois.close();
    }
    @Test
    public void test01() throws FileNotFoundException, IOException{
        Message msg = new Message("Teacher Chai", "Teacher Tong", "Add salary", System.currentTimeMillis());
        
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("message.dat"));
        oos.writeObject(msg);
        oos.close();
    }
}
class Message implements Serializable{
​
    private static final long serialVersionUID = 1L;
    private String fromUser;
    private String toUser;
    private String content;
    private long sendTime;
    public Message(String fromUser, String toUser, String content, long sendTime) {
        super();
        this.fromUser = fromUser;
        this.toUser = toUser;
        this.content = content;
        this.sendTime = sendTime;
    }
    public Message() {
        super();
    }
    public String getFromUser() {
        return fromUser;
    }
    public void setFromUser(String fromUser) {
        this.fromUser = fromUser;
    }
    public String getToUser() {
        return toUser;
    }
    public void setToUser(String toUser) {
        this.toUser = toUser;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public long getSendTime() {
        return sendTime;
    }
    public void setSendTime(long sendTime) {
        this.sendTime = sendTime;
    }
    @Override
    public String toString() {
        return "Message [fromUser=" + fromUser + ", toUser=" + toUser + ", content=" + content + ", sendTime="
                + sendTime + "]";
    }
}

Question 7

Case:

1. Input three sentences from the keyboard and print to a word with PrintStream Txt file

2. Then use Scanner to read the display line by line

package com.atguigu.test07;
​
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;
​
import org.junit.Test;
​
public class Test07 {
    @Test
    public void test02() throws FileNotFoundException{
        Scanner input = new Scanner(new File("words.txt"));
        while(input.hasNextLine()){
            System.out.println(input.nextLine());
        }
        input.close();
    }
    
    
    @Test
    public void test01() throws FileNotFoundException{
        Scanner input = new Scanner(System.in);
        PrintStream ps = new PrintStream("words.txt");
        for (int i = 0; i < 3; i++) {
            System.out.println("Please enter page" + (i+1) + "What to say to Mr. Chai:");
            String content = input.nextLine();
            ps.println(content);
        }
        input.close();
        ps.close();
    }
}
​

recursion

Question 8

Case: get all the data in atguigu folder of disk D java file

(1) No subfolders

(2) Include subfolders

package com.atguigu.test08;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;

import org.junit.Test;

public class Test08 {
	@Test
	public void test01(){
		File  file = new File("D:/atguigu");
		//Do not include in subfolders
		File[] listFiles = file.listFiles(new FileFilter() {
			
			@Override
			public boolean accept(File pathname) {
				
				return pathname.getName().endsWith(".java");
			}
		});
		for (File sub : listFiles) {
			System.out.println(sub);
		}
	}
	
	@Test
	public void test02() {
		File  file = new File("D:/atguigu");
		//Include in subfolders
		ArrayList<String> all = listAllSubs(file);
		for (String string : all) {
			System.out.println(string);
		}
	}
	
	public ArrayList<String> listAllSubs(File file){
		ArrayList<String> list = new ArrayList<>();
		if(file.isFile()){
			if(file.getName().endsWith(".java")){
				list.add(file.getPath());
			}
		}else if(file.isDirectory()){
			File[] listFiles = file.listFiles();
			for (File sub : listFiles) {
				list.addAll(listAllSubs(sub));
			}
		}
		return list;
	}
}

Question 9

Case: Statistics on the folder size of Chai Linyan _JavaSE, class 190513, Shangsi Valley

package com.atguigu.test09;

import java.io.File;

import org.junit.Test;

public class Test09 {
	@Test
	public void test01(){
		File file = new File("d:/Shang Silicon Valley_190513 class_Chai Linyan_JavaSE");
		long size = size(file);
		System.out.println("Total folder size:" + size);
	}
	public long size(File file){
		if(file.isFile()){
			return file.length();
		}else if(file.isDirectory()){
			File[] listFiles = file.listFiles();
			long sum = 0;
			for (File sub : listFiles) {
				sum += size(sub);
			}
			return sum;
		}
		return 0;
	}
}

Question 10

Case: copy Chai Linyan _javaseof class 190513 in Shangsi Valley to the testIO folder of the current project

package com.atguigu.test10;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.junit.Test;

public class Test10 {
	@Test
	public void test01() throws IOException{
		File src = new File("d:/Homework and grades");
		File dest = new File("testIO");
		copyDir(src, dest);
	}
	
	public void copyDir(File src, File dest) throws IOException{
		if(dest.isFile()){
			throw new RuntimeException(dest +"Not a folder");
		}
		if(src.isFile()){
			File destFile = new File(dest.getPath()+"/" + src.getName());
			copyFile(src, destFile);
		}else if(src.isDirectory()){
			File destFile = new File(dest.getPath()+"/" + src.getName());
			destFile.mkdir();
			
			File[] listFiles = src.listFiles();
			for (File sub : listFiles) {
				copyDir(sub,destFile);
			}
		}
	}
	
	public void copyFile(File srcFile, File destFile) throws IOException{
		FileInputStream fis = new FileInputStream(srcFile);
		FileOutputStream fos = new FileOutputStream(destFile);
		byte[] data = new byte[1024];
		int len;
		while((len = fis.read(data)) !=-1){
			fos.write(data, 0, len);
		}
		fis.close();
		fos.close();
	}
}

Question 11

Case: delete the testIO folder of the current project

package com.atguigu.test11;

import java.io.File;

import org.junit.Test;

public class Test11 {
	@Test
	public void test01(){
		deleteDir(new File("testIO"));
	}
	
	public void deleteDir(File dir){
		if(dir.isDirectory()){
			File[] listFiles = dir.listFiles();
			for (File sub : listFiles) {
				deleteDir(sub);
			}
		}
		
		dir.delete();
	}
}

Question 12

Case: cut Chai Linyan _javaseof class 190513 in Shangsi valley into the testIO folder of the current project

package com.atguigu.test12;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.junit.Test;

public class Test12 {
	@Test
	public void test01() throws IOException{
		File src = new File("testIO");
		File dest = new File("testIO2");
		cutDir(src, dest);
	}
	
	public void cutDir(File src, File dest) throws IOException{
		if(dest.isFile()){
			throw new RuntimeException(dest +"Not a folder");
		}
		if(src.isFile()){
			File destFile = new File(dest.getPath()+"/" + src.getName());
			copyFile(src, destFile);
		}else if(src.isDirectory()){
			File destFile = new File(dest.getPath()+"/" + src.getName());
			destFile.mkdir();
			
			File[] listFiles = src.listFiles();
			for (File sub : listFiles) {
				cutDir(sub,destFile);
			}
		}
		src.delete();
	}
	
	public void copyFile(File srcFile, File destFile) throws IOException{
		FileInputStream fis = new FileInputStream(srcFile);
		FileOutputStream fos = new FileOutputStream(destFile);
		byte[] data = new byte[1024];
		int len;
		while((len = fis.read(data)) !=-1){
			fos.write(data, 0, len);
		}
		fis.close();
		fos.close();
	}
}

Chapter 20

Question 1

Case: the client simulates student consultation and the server simulates teacher consultation for interaction.

Client received message:

Welcome to Silicon Valley

It's full. Please report the next issue

Information received by the server:

Hello, I want to sign up for the employment class

All right, bye!

Development tips:

(1) How to implement the interaction between a client and a server

(2) If multiple clients interact with the server, how to implement it

package com.atguigu.test01;
​
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
​
public class Test01Client {
    public static void main(String[] args)  throws IOException {
        Socket socket = new Socket("127.0.0.1", 8888); // Create a Socket and specify the ip address and port number
        // Get input stream
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        System.out.println(br.readLine());
​
        // Get output stream
        PrintStream ps = new PrintStream(socket.getOutputStream());
        ps.println("Hello, I want to sign up for the employment class");
​
        System.out.println(br.readLine());
​
        ps.println("All right, bye!");
        
        socket.close();
    }
}
​
package com.atguigu.test01;
​
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.time.LocalDateTime;
​
public class Test01Server1 {
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(8888);
        Socket socket = server.accept();
        
        // Get output stream
        PrintStream ps = new PrintStream(socket.getOutputStream());
        ps.println("Welcome to Silicon Valley");
​
        // Get input stream
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        System.out.println(socket.getInetAddress().getHostAddress() + "Leaving a message." + LocalDateTime.now());
        System.out.println(br.readLine() + "\n");
​
        ps.println("The newspaper is full,Please report the next issue");
​
        System.out.println(socket.getInetAddress().getHostAddress() + "Leaving a message." + LocalDateTime.now());
        System.out.println(br.readLine());
        
        socket.close();
        server.close();
    }
}
package com.atguigu.test01;
​
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.time.LocalDateTime;
​
public class Test01Server2 {
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(8888);
        boolean flag = true;
        while(flag){
            Socket socket = server.accept();
            new Thread(){
                public void run(){
                    try {
                        // Get output stream
                        PrintStream ps = new PrintStream(socket.getOutputStream());
                        ps.println("Welcome to Silicon Valley");
    
                        // Get input stream
                        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        System.out.println(socket.getInetAddress().getHostAddress() + "Leaving a message." + LocalDateTime.now());
                        System.out.println(br.readLine() + "\n");
    
                        ps.println("The newspaper is full,Please report the next issue");
    
                        System.out.println(socket.getInetAddress().getHostAddress() + "Leaving a message." + LocalDateTime.now());
                        System.out.println(br.readLine());
                        
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
        server.close();
    }
}

Question 2

Case: simulate the client to input the Chinese to be queried, and the server returns the corresponding English words

The effects are as follows:

Development tips:

(1) There is a map on the server side. key is a Chinese word and value is the corresponding word

(2) After the server receives the word from the client, it get s it from the map. If it can be found, it returns the word. If it cannot be found, it returns "not found"

package com.atguigu.test02;
​
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
​
public class Test02Server {
    public static void main(String[] args) throws IOException {
        HashMap<String, String> dictionary = new HashMap<String, String>();
        dictionary.put("Monday", "Monday");
        dictionary.put("Tuesday", "Tuesday");
        dictionary.put("Wednesday", "Wednesday");
        dictionary.put("Thursday", "Thursday");
        dictionary.put("Friday", "Friday");
        dictionary.put("Saturday", "Saturday");
        dictionary.put("Sunday", "Sunday");
        //...
        
        ServerSocket server = new ServerSocket(8888);
        Socket socket = server.accept();
        
        // Get input stream
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        // Get output stream
        PrintStream ps = new PrintStream(socket.getOutputStream());
        
        //Receive client's Chinese
        String key = br.readLine();
        //Query the corresponding English words and return the results
        String words = dictionary.get(key);
        if(words != null){
            ps.println(words);
        }else{
            ps.println("o(╥﹏╥)o No corresponding word found!");
        }
        
        socket.close();
        server.close();
    }
}
​
package com.atguigu.test02;
​
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
​
public class Test02Client {
    public static void main(String[] args)  throws IOException {
        // Create a Socket and specify the ip address and port number
        Socket socket = new Socket("127.0.0.1", 8888);
        
        Scanner input = new Scanner(System.in);
        System.out.print("Please enter the words to query:");
        String content = input.next();
        
        // Get output stream
        PrintStream ps = new PrintStream(socket.getOutputStream());
        ps.println(content);
        
        // Get input stream
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        System.out.println("Query results:" + br.readLine());
        
        socket.close();
        input.close();
    }
}

Question 3

Case: the client uploads photos to the server

Requirements: (1) the photos uploaded by the client must be in jpg format and within 2M (inclusive), otherwise they cannot be uploaded

(2) After the upload is successful, the server will return the upload success. If the upload fails, the server will return the upload failure

(3) The photos uploaded by the client to the server are stored in the folder "photo" under the project name and named "photo original file name + timestamp. jpg"

The effects are as follows:

package com.atguigu.test03;
​
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
​
public class Test03Server{
    public static void main(String[] args) throws IOException {
        //Turn on the server
        ServerSocket server = new ServerSocket(8888);
        //Receive a client connection
        Socket socket = server.accept();
        //Get input stream
        DataInputStream dis = new DataInputStream(socket.getInputStream());
        //Get output stream
        PrintStream ps = new PrintStream(socket.getOutputStream());
        //(1) Read the file name first
        String filename = dis.readUTF();
        
        //(2) Generate a unique file name
        String destfile = "photo" + "/" +  filename + System.currentTimeMillis() + ".jpg";
        
        //(3) Read the contents of the file and write to the target file
        FileOutputStream fos = new FileOutputStream(destfile);
        try {
            byte[] data = new byte[1024];
            int len;
            while((len = dis.read(data)) != -1){
                fos.write(data, 0, len);
            }
            //Return results to the client
            ps.println("Received successfully!");
        } catch (Exception e) {
            //Return results to the client
            ps.println("Receiving failed!");
        }finally{
            fos.close();
        }
        server.close();
    }
}
​
package com.atguigu.test03;
​
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Scanner;
​
public class Test03Client {
    public static void main(String[] args)throws IOException {
        //Connect server
        Socket socket= new Socket("127.0.0.1",8888);
        
        //Select the file to upload
        Scanner input = new Scanner(System.in);
        System.out.println("Please select the file to upload:");
        //For example: D: \ Silicon Valley_ Class 0325_ Chai Linyan_ JavaSE \ notes \ Chapter 14 IO stream docx
        String fileStr  = input.nextLine();
        File file = new File(fileStr);
        
        if(!fileStr.endsWith(".jpg")){
            System.out.println("Photos must be.jpg format");
            input.close();
            socket.close();
            return;
        }
        if(file.length()>1024*1024*2){
            System.out.println("Photos must be in 2 M(contain)within");
            input.close();
            socket.close();
            return;
        }
        
        DataOutputStream dos = null;
        //Read the content from the file and send it to the server
        FileInputStream fis = null;
        try {
            //Get output stream
            dos = new DataOutputStream(socket.getOutputStream());
            //Send file name first
            dos.writeUTF(file.getName().substring(0, file.getName().lastIndexOf(".")));
            //Send file content
            fis = new FileInputStream(file);
            byte[] data = new byte[1024];
            int len;
            while((len = fis.read(data)) !=-1){
                dos.write(data, 0, len);
            }
            socket.shutdownOutput();//Tell the server that I have sent it
        } catch (Exception e) {
            System.out.println("Upload failed");
        }finally{
            fis.close();
            dos.close();
        }
        
        //Receive results
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String result = br.readLine();
        System.out.println(result);
        
        br.close();
        socket.close();
        input.close();
    }
​
}
​

Question 4

Case: simulate sending "welcome to Silicon Valley" to all students

Development tips: use UDP group sending

package com.atguigu.test04;
​
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
​
public class Test04Send {
    public static void main(String[] args)throws Exception {
        //(1) First create a datagram socket
        DatagramSocket ds = new DatagramSocket();
        
        //(2) Ready to send data
        String str = "Welcome to Silicon Valley";
        byte[] data = str.getBytes();
        
        for (int i = 0; i <= 255; i++) {
            //(3) Wrap the data into a datagram
            //DatagramPacket(byte[] buf, int length, InetAddress address, int port)
            /*
             * First parameter: byte array of data to be sent
             * The second parameter: the length of the array
             * The third parameter: the IP address of the receiver
             * The third parameter: the port number of the receiver
             * 
             * For example, for express delivery, you need to fill in the IP and port number of the receiver
             */
            InetAddress ip = InetAddress.getByName("192.168.11."+i);
            int port = 8888;
            DatagramPacket dp = new DatagramPacket(data,data.length,ip,port);
            
            try {
                //(4) Send datagram
                //Send via socket
                ds.send(dp);
            } catch (Exception e) {
            }
        }
        
        
        //(5) Disconnect
        ds.close();
    }
}
​
package com.atguigu.test04;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class Test04Receiver {
	public static void main(String[] args)throws Exception {
		//1. Prepare a socket to receive messages
		//The receiver first determines the port number and listens to the port number of the data
		//For example, to receive express delivery, you need to determine your address and mobile phone number before the other party can send it to you
		DatagramSocket ds = new DatagramSocket(8888);
		
		//2. Prepare a datagram to receive data
		//DatagramPacket(byte[] buf, int length)
		byte[] data = new byte[1024*64];//64K
		DatagramPacket dp = new DatagramPacket(data,data.length);
		
		//3. Receive data
		ds.receive(dp);
		
		//4. Unpack
		byte[] result = dp.getData();
		int len = dp.getLength();//Length of data actually received
		System.out.println(new String(result,0,len));
		
		//5. Shut down
		ds.close();
	}
}

Chapter 21

Question 1

Case: get the information of a class with reflection, and use a class with reflection

Development tips:

1. Declare a class: com atguigu. test01. demo. AtguiguDemo,

(1) Contains static variables: School (explicitly initialized as "school")

(2) Include attribute: class name className

(3) It also provides constructors, get/set, etc

(4) Implement Serializable and Comparable interfaces (sorted by class name)

2. Put com atguigu. test01. demo. Export atguigu democlass as an atguigu Jar and put it in D: \ program files \ Java \ jdk1 8.0_ 141 \ JRE \ lib \ ext directory (note that your own JDK installation directory shall prevail)

3. In the test01() test method of test Class Test01, use reflection to obtain the Class object of AtguiguDemo Class and obtain all its information, including Class loader, package name, Class name, parent Class, parent interface, attribute, constructor, methods, etc.

4. In the test02() test method of test class Test01, use reflection to obtain the value of school, modify the value of school to "Shang Silicon Valley University", and then obtain the value of school

5. In the test03() test method of test class Test01, create the object of AtguiguDemo class with reflection, set the value of class name className property, and get its value

6. In the test04() test method of the test class Test01, create two objects of AtguiguDemo class with the reflection obtained parameter structure, obtain the compareTo method, call the compareTo method, and compare the size.

package com.atguigu.test01;
​
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.util.Arrays;
​
import org.junit.Test;
​
public class Test01 {
    @Test
    public void test01() throws ClassNotFoundException{
        Class clazz = Class.forName("com.atguigu.test01.demo.AtguiguDemo");
        
        ClassLoader classLoader = clazz.getClassLoader();
        System.out.println("Class loader:" + classLoader);
        
        Package pkg = clazz.getPackage();
        System.out.println("Package name:" + pkg.getName());
        
        int cMod = clazz.getModifiers();
        System.out.println("Class modifier:" + Modifier.toString(cMod));
        
        System.out.println("Class name:" + clazz.getName());
        System.out.println("Parent class:" + clazz.getSuperclass().getName());
        Class[] interfaces = clazz.getInterfaces();
        System.out.println("Parent interfaces:"+Arrays.toString(interfaces));
        
        Field[] declaredFields = clazz.getDeclaredFields();
        for (int i =0 ;i<declaredFields.length; i++) {
            System.out.println("The first" + (i+1) + "Fields:");
            int fMod = declaredFields[i].getModifiers();
            System.out.println("Modifier:" + Modifier.toString(fMod));
            System.out.println("Data type:"  + declaredFields[i].getType().getName());
            System.out.println("Property name:" + declaredFields[i].getName());
        }
        
        Constructor[] declaredConstructors = clazz.getDeclaredConstructors();
        for (int i = 0; i < declaredConstructors.length; i++) {
            System.out.println("The first" + (i+1) + "Constructors:");
            int csMod = declaredConstructors[i].getModifiers();
            System.out.println("Modifier:" + Modifier.toString(csMod));
            System.out.println("Constructor Name:" + declaredConstructors[i].getName());
            System.out.println("Formal parameter list:" + Arrays.toString(declaredConstructors[i].getParameterTypes()));
        }
        
        Method[] declaredMethods = clazz.getDeclaredMethods();
        for (int i = 0; i < declaredMethods.length; i++) {
            System.out.println("The first" + (i+1) + "Member methods:");
            int csMod = declaredMethods[i].getModifiers();
            System.out.println("Modifier:" + Modifier.toString(csMod));
            System.out.println("Return value type:" + declaredMethods[i].getReturnType().getName());
            System.out.println("Method name:" + declaredMethods[i].getName());
            System.out.println("Formal parameter list:" + Arrays.toString(declaredMethods[i].getParameterTypes()));
        }
    }
    
    @Test
    public void test02() throws Exception{
        Class clazz = Class.forName("com.atguigu.test01.demo.AtguiguDemo");
        Field field = clazz.getDeclaredField("school");
        field.setAccessible(true);
        Object value = field.get(null);
        System.out.println("school = " + value);
        
        field.set(null, "Shang Silicon Valley University");
        value = field.get(null);
        System.out.println("school = " + value);
    }
    
    @Test
    public void test03() throws Exception{
        Class clazz = Class.forName("com.atguigu.test01.demo.AtguiguDemo");
        Object object = clazz.newInstance();
        Field field = clazz.getDeclaredField("className");
        field.setAccessible(true);
        Object value = field.get(object);
        System.out.println("className = " + value);
        
        field.set(object, "190513 class");
        value = field.get(object);
        System.out.println("className = " + value);
    }
    
    @Test
    public void test04() throws Exception{
        Class clazz = Class.forName("com.atguigu.test01.demo.AtguiguDemo");
        Constructor c = clazz.getDeclaredConstructor(String.class);
        Object obj1 = c.newInstance("190513BJ class");
        Object obj2 = c.newInstance("190325SH class");
        
        Method m = clazz.getDeclaredMethod("compareTo", Object.class);
        System.out.println("obj1 And obj2 Comparison results:" + m.invoke(obj1, obj2));
    }
}
​
package com.atguigu.test01.demo;
​
import java.io.Serializable;
​
public class AtguiguDemo implements Serializable,Comparable<AtguiguDemo>{
    private static final long serialVersionUID = 1L;
    private static String school = "Shang Silicon Valley";
    private String className;
    public AtguiguDemo(String className) {
        super();
        this.className = className;
    }
    public AtguiguDemo() {
        super();
    }
    public static String getSchool() {
        return school;
    }
    public static void setSchool(String school) {
        AtguiguDemo.school = school;
    }
    public String getClassName() {
        return className;
    }
    public void setClassName(String className) {
        this.className = className;
    }
    @Override
    public String toString() {
        return "AtguiguDemo [className=" + className + "]";
    }
    @Override
    public int compareTo(AtguiguDemo o) {
        return this.className.compareTo(o.getClassName());
    }
}
​

Question 2

Case: Juicer juicing cases, including fruit, apple, banana, orange and squeeze

effect:

Development tips:

1. Declare (Fruit) fruit interface, including juicing abstract method: void squeeze();

2, declare the Juicer, including the running method: public void run(Fruit f), the method of body calling, the juice extraction method of F squeeze().

3. Declare various fruit classes, implement the fruit interface, and rewrite squeeze();

4. Under src, create the configuration file: config Properties, and add fruitName=xxx in the configuration file (where xx is the full class name of a certain fruit)

5. In the Test02 test class,

(1) Read the configuration file, get the fruit class name, and create a fruit object with reflection,

(2) Create the juicer object and call the run() method

package com.atguigu.test02;
​
import java.util.Properties;
​
public class Test02 {
    public static void main(String[] args) throws Exception {
        Properties pro = new Properties();
        pro.load(Test02.class.getClassLoader().getResourceAsStream("config.properties"));
        Class<?> clazz = Class.forName(pro.getProperty("fruitName"));
        Fruit f = (Fruit) clazz.newInstance(); 
        Juicer j = new Juicer();
        j.run(f);
    }
​
}
​
interface Fruit {
    public void squeeze();
}
​
class Juicer {
    public void run(Fruit f) {
        f.squeeze();
    }
​
}
class Apple implements Fruit {
    public void squeeze() {
        System.out.println("Squeeze out a glass of apple juice");
    }
}
​
class Orange implements Fruit {
    public void squeeze() {
        System.out.println("Squeeze out a glass of orange juice");
    }
}
​
​

Question 3

Code blank

package com.atguigu.test03;
​
import java.lang.reflect.ParameterizedType;
​
public class Test03 {
    public static void main(String[] args) {
        SubA a = new SubA();
        System.out.println(a.getType());
        
        SubB b = new SubB();
        System.out.println(b.getType());
    }
}
abstract class Base<T>{
    private Class type;
    
    public Base(){
        //The actual type assigned T to the type attribute
        
        _____________________________________
    }
​
    public Class getType() {
        return type;
    }
}
class SubA extends Base<String>{
​
}
class SubB extends Base{
​
}
package com.atguigu.test03;
​
import java.lang.reflect.ParameterizedType;
​
public class Test03 {
    public static void main(String[] args) {
        SubA a = new SubA();
        System.out.println(a.getType());
        
        SubB b = new SubB();
        System.out.println(b.getType());
    }
}
abstract class Base<T>{
    private Class type;
    
    public Base(){
        Class<? extends Base> clazz = this.getClass();
        try {
            ParameterizedType pt = (ParameterizedType) clazz.getGenericSuperclass();
            type = (Class) pt.getActualTypeArguments()[0];
        } catch (Exception e) {
            type = Object.class;
        }
    }
​
    public Class getType() {
        return type;
    }
}
class SubA extends Base<String>{
​
}
class SubB extends Base{
​
}

Question 4

Case:

1. Declare custom annotation @ Table

(1) Add the configuration parameter value of String type

(2) And limit the use position of @ Table to class

(3) And specify the lifecycle as runtime

2. Declare custom annotation @ Column

(1) Add the configuration parameter name of String type to represent the column name of the table

(2) The configuration parameter type of String type is added to indicate the column data type of the table

(3) And limit the use position of @ Column on the property

(4) And specify the lifecycle as runtime

3. Declare the User class,

(1) Attributes: id, username, password, email

(2) On the User class, mark the @ Table annotation and assign value to "t_user"

(3) Mark @ Column on each attribute of the User class and assign values to name and type, for example:

id: name is assigned no and type is assigned int

Username: name is assigned as username, and type is assigned as varchar(20)

password: name is assigned pwd and type is assigned char(6)

Email: name is assigned as email, and type is assigned as varchar(50)

4. In the test class Test04, get the annotation of User class and each attribute declaration through reflection, and get the annotation value

Operation effect:

package com.atguigu.test04;
​
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
​
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
    String value();
}
​
package com.atguigu.test04;
​
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
​
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
    String name();
    String type();
}
package com.atguigu.test04;
​
@Table("t_user")
public class User {
    @Column(name="no",type="int")
    private int id;
    
    @Column(name="username",type="varchar(20)")
    private String username;
    
    @Column(name="pwd",type="char(6)")
    private String password;
    
    @Column(name="email",type="varchar(50)")
    private String email;
    
    public User(int id, String username, String password, String email) {
        super();
        this.id = id;
        this.username = username;
        this.password = password;
        this.email = email;
    }
    public User() {
        super();
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", password=" + password + ", email=" + email + "]";
    }
    
}
package com.atguigu.test04;

import java.lang.reflect.Field;

public class Test04 {
	public static void main(String[] args) throws Exception {
		Class clazz = User.class;
		
		Table t = (Table) clazz.getAnnotation(Table.class);
		String table = t.value();
		System.out.println("User Database table corresponding to class:" + table);
		
		Field idField = clazz.getDeclaredField("id");
		Column idColumn = idField.getAnnotation(Column.class);
		String idName = idColumn.name();
		String idType = idColumn.type();
		System.out.println("id Property corresponds to the fields of the database table:" + idName + ",Type:" + idType);
		
		Field usernameField = clazz.getDeclaredField("username");
		Column usernameColumn = usernameField.getAnnotation(Column.class);
		String usernameName = usernameColumn.name();
		String usernameType = usernameColumn.type();
		System.out.println("username Property corresponds to the fields of the database table:" + usernameName + ",Type:" + usernameType);
		
		Field passwordField = clazz.getDeclaredField("password");
		Column passwordColumn = passwordField.getAnnotation(Column.class);
		String passwordName = passwordColumn.name();
		String passwordType = passwordColumn.type();
		System.out.println("password Property corresponds to the fields of the database table:" + passwordName + ",Type:" + passwordType);
		
		Field emailField = clazz.getDeclaredField("email");
		Column emailColumn = emailField.getAnnotation(Column.class);
		String emailName = emailColumn.name();
		String emailType = emailColumn.type();
		System.out.println("email Property corresponds to the fields of the database table:" + emailName + ",Type:" + emailType);
	}
}

Chapter Twenty-Two

Question 1

Case:

1. Define a functional interface CurrentTimePrinter, in which the abstract method void printCurrentTime() uses the annotation @ FunctionalInterface

2. Define public static void showLongTime(CurrentTimePrinter timePrinter) in the test class. The expected behavior of this method is to use timePrinter to print the current system time

3. Test showLongTime(), and complete the requirement through lambda expression

(1) Implementation 1: print the millisecond value of the current system time, and use system currentTimeMillis()

(2) Implementation 2: print the current system time with Date

(3) Implementation 3: print and localize the current system time, using LocalDateTime

package com.atguigu.test01;
​
import java.time.LocalDateTime;
import java.util.Date;
​
public class Test01 {
    
    public static void main(String[] args) {
        showLongTime(() -> System.out.println(System.currentTimeMillis()));
        showLongTime(() -> System.out.println(new Date()));
        showLongTime(() -> System.out.println(LocalDateTime.now()));
    }
    
    public static void showLongTime(CurrentTimePrinter timePrinter){
        timePrinter.printCurrentTime();
    }
}
@FunctionalInterface
interface CurrentTimePrinter{
    void printCurrentTime();
}

Question 2

Case:

1. Define a functional interface IntCalc, in which the abstract method int cal (int a, int b) uses the annotation @ functionalinterface2. Define public static void getproduct (int a, int b, IntCalc tools) in the test class. The expected behavior of this method prints the calculation results of cal(a,b) using tools. 3. Test getProduct(). Complete the requirements through lambda expression, where a = 1 and B = 2

(1) Realization 1: find the sum of a and B

(2) Realization 2: find the difference between a and B

(3) Realization 3: find the product of a and B

(4) Realization 4: find the quotient of a and B

(5) Realization 5: find the bitwise and of a and B

(6) Realization 6: find a < < B

package com.atguigu.test02;
​
public class Test02 {
    public static void main(String[] args) {
        getProduct(1,2,(a,b) -> a+b);
        getProduct(1,2,(a,b) -> a-b);
        getProduct(1,2,(a,b) -> a*b);
        getProduct(1,2,(a,b) -> a/b);
        getProduct(1,2,(a,b) -> a&b);
        getProduct(1,2,(a,b) -> a<<b);
    }
    
    public static void getProduct(int a , int b ,IntCalc tools){
        System.out.println("result:" + tools.cal(a, b));
    }
}
@FunctionalInterface
interface IntCalc{
    int cal(int a , int b);
}

Question 3

Case:

1. The test class code is given as follows:

package com.atguigu.test03;
​
import java.util.function.Supplier;
​
public class Test03 {
    public static <T> T getObj(Supplier<T> supplier) {
        return supplier.get();
    }
​
    public static void main(String[] args) {
        ....
    }
}
​

2. Use lambda expressions to obtain the following objects:

  • String array with length of 5

  • HashSet < integer > set containing 5 random numbers between 1-20 (including 1 and 20)

  • A Calendar object representing April 1, 2018

package com.atguigu.test03;
​
import java.util.Arrays;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.Random;
import java.util.function.Supplier;
​
public class Test03 {
    public static <T> T getObj(Supplier<T> supplier) {
        return supplier.get();
    }
​
    public static void main(String[] args) {
        String[] arr = getObj(() -> new String[5]);
        System.out.println(Arrays.toString(arr));
        
        Random rand = new Random();
        HashSet<Integer> nums = getObj(() -> {
            HashSet<Integer> set = new HashSet<Integer>();
            while(set.size()<5){
                set.add(rand.nextInt(20)+1);
            }
            return set;
        });
        System.out.println(nums);
        
        GregorianCalendar obj = getObj(() -> new GregorianCalendar(2019,5,13));
        System.out.println(obj);
    }
}
​

Question 4

Case:

1. The test class code is given as follows:

package com.atguigu.test04;
​
import java.util.HashMap;
import java.util.function.Consumer;
​
public class Test04 {
    public static <T> void doJob(T t, Consumer<T> consumer) {
        consumer.accept(t);
    }
​
    public static <T> void doJob(T t, Consumer<T> consumer1, Consumer<T> consumer2) {
        consumer1.andThen(consumer2).accept(t);
    }
​
    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();
​
        // key: name value: Score
        map.put("CEN Xiaocun", 59);
        map.put("Gu Tianluo", 82);
        map.put("Zha Zha Hui", 98);
        map.put("LAN Xiaoyue", 65);
        map.put("Tens of thousands of skin", 70);
        
    }
}

2. Use lambda expressions to fulfill the following requirements

  • Print Gu Tianluo's score

  • Print highest score

  • Take 60 points and 70 points as the passing line respectively, and print the name of the qualified person (combined consumption)

package com.atguigu.test04;
​
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
​
public class Test04 {
    public static <T> void doJob(T t, Consumer<T> consumer) {
        consumer.accept(t);
    }
​
    public static <T> void doJob(T t, Consumer<T> consumer1, Consumer<T> consumer2) {
        consumer1.andThen(consumer2).accept(t);
    }
​
    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();
​
        // key: name value: Score
        map.put("CEN Xiaocun", 59);
        map.put("Gu Tianluo", 82);
        map.put("Zha Zha Hui", 98);
        map.put("LAN Xiaoyue", 65);
        map.put("Tens of thousands of skin", 70);
        
        //Print Gu Tianluo's score
        doJob(map, (m) -> System.out.println("Gu Tianluo's score:" + m.get("Gu Tianluo")));
​
        //Print highest score
        doJob(map, (m) -> System.out.println("Highest score:" + Collections.max(m.values())));
​
        //Print the name of the person who passed
        doJob(map, (m) -> {
            System.out.print("60 Passing person:");
            for (Map.Entry<String, Integer> entry : m.entrySet()) {
                if (entry.getValue()>=60){
                    System.out.print(entry.getKey()+" ");
                }
            }
            System.out.println();
        }, (m) -> {
            System.out.print("70 Passing person:");
            for (Map.Entry<String, Integer> entry : m.entrySet()) {
                if (entry.getValue()>=70){
                    System.out.print(entry.getKey()+" ");
                }
            }
            System.out.println();
        });
    }
}
​

Question 5

Case:

1. Define student class: (1) member variable name: String name; (2) member variable score: int score; (3) no parameter and full parameter construction (4) Rewrite toString()

2. In the test class, complete the following requirements: (1) add five students to the ArrayList collection (2) use collections Sort (list < T > list, Comparator <? Super T > c) method sorts students' grades from small to large, which is implemented in the following three forms: a. use anonymous inner class , b. use Lambda expression , c. use method reference / / tips: use the static method comparingInt() method in the Comparator interface

3. Student information and grades are as follows:

full namemathematics
Nicholas Tse85
Zhang Ziyi63
Liu Yifei77
Huang Xiaoming33
CEN Xiaocun92
package com.atguigu.test05;
​
public class Student {
    private String name;
    private int score;
    
    public Student() {
    }
​
    public Student(String name, int score) {
        this.name = name;
        this.score = score;
    }
    
    public String getName() {
        return name;
    }
​
    public void setName(String name) {
        this.name = name;
    }
​
    public int getScore() {
        return score;
    }
​
    public void setScore(int score) {
        this.score = score;
    }
​
    @Override
    public String toString() {
        return "Student{" + "name='" + name + '\'' + ", score=" + score + '}';
    }
}
package com.atguigu.test05;
​
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
​
public class Test05 {
    public static void main(String[] args) {
        ArrayList<Student> list = new ArrayList<>();
        list.add(new Student("Nicholas Tse", 85));
        list.add(new Student("Zhang Ziyi", 63));
        list.add(new Student("Liu Yifei", 77));
        list.add(new Student("Huang Xiaoming", 33));
        list.add(new Student("CEN Xiaocun", 92));
​
        // Use anonymous inner classes to sort grades from small to large
        Collections.sort(list, new Comparator<Student>() {
​
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getScore() - o2.getScore();
            }
        });
​
        // Use Lambda to rank English scores from small to large
        Collections.sort(list, (o1, o2) -> o1.getScore() - o2.getScore());
​
        // Using method references with comparingInt()
        Collections.sort(list, Comparator.comparingInt(Student::getScore));
​
        System.out.println(list);
    }
}
​

Question 6

Case:

1. Declare an Employee type, including number, name, salary, age and gender

2. Declare an employee management class,

(1) ArrayList is used in the management class to store all employee objects

(2) Declare the public void add(Employee emp) method to add employees

(3) Declare the public ArrayList get (predict < employee > P) method to filter qualified employees according to conditions

(4) Declare the public void remove (predict < employee > P) method, which can be deleted according to conditions

(5) Declare the public void update (consumer < employee > c) method to perform the operation specified by c on the elements in the collection

3. In test class

(1) Add 5 employee objects to the managed collection

(2) Filter out

① Employees with even numbers

② Employees with salary less than 10000

③ Female employees older than 30

④ An employee surnamed Zhang

⑤ All employees

(3) Delete

① Female employees older than 30

② Delete the employee "Zhang San"

(4) Give each employee a 10% salary increase

package com.atguigu.test06;

public class Employee {
	private int id;
	private String name;
	private double salary;
	private int age;
	private char gender;
	public Employee(int id, String name, double salary, int age, char gender) {
		super();
		this.id = id;
		this.name = name;
		this.salary = salary;
		this.age = age;
		this.gender = gender;
	}
	public Employee() {
		super();
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getSalary() {
		return salary;
	}
	public void setSalary(double salary) {
		this.salary = salary;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public char getGender() {
		return gender;
	}
	public void setGender(char gender) {
		this.gender = gender;
	}
	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", salary=" + salary + ", age=" + age + ", gender=" + gender
				+ "]";
	}
}

package com.atguigu.test06;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.function.Consumer;
import java.util.function.Predicate;

public class EmployeeService {
	private ArrayList<Employee> list;
	
	public EmployeeService(){
		list = new ArrayList<Employee>();
	}
	
	public void add(Employee emp){
		list.add(emp);
	}
	
	public ArrayList<Employee> get(Predicate<Employee> p){
		ArrayList<Employee> all = new ArrayList<Employee>();
		for (Employee employee : list) {
			if(p.test(employee)){
				all.add(employee);
			}
		}
		return all;
	}
	
	public void remove(Predicate<Employee> p){
		Iterator<Employee> iterator = list.iterator();
		while(iterator.hasNext()){
			Employee next = iterator.next();
			if(p.test(next)){
				iterator.remove();
			}
		}
	}
	
	public void update(Consumer<Employee> c){
		for (Employee employee : list) {
			c.accept(employee);
		}
	}
	
	public int size(){
		return list.size();
	}
}

package com.atguigu.test06;

import java.util.ArrayList;

import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;

public class Test06 {
	private static EmployeeService es = new EmployeeService();
	@BeforeClass
	public static void test01(){
		es.add(new Employee(1, "Zhang San", 8000, 23, 'male'));
		es.add(new Employee(2, "Wang Xiaoer", 12000, 22, 'male'));
		es.add(new Employee(3, "Li Si", 12000, 24, 'female'));
		es.add(new Employee(4, "Wang Wu", 11000, 34, 'female'));
		es.add(new Employee(5, "Zhao Liu", 6000, 34, 'female'));
	}
	@Test
	public void testSize(){
		System.out.println("Current number of employees:" + es.size());
	}
	
	@Test
	public void testRemove1(){
		//Delete female employees older than 30
		System.out.println("Delete female employees older than 30");
		es.remove(e->e.getAge()>30 && e.getGender()=='female');
	}
	
	@Test
	public void testRemove2(){
		//Delete the employee "Zhang San"
		System.out.println("Delete the employee "Zhang San"");
		es.remove(e->e.getName().startsWith("Zhang"));
	}
	
	@Test
	public void testRemove3(){
		System.out.println("Everyone's salary increased by 10%");
		es.update(e -> e.setSalary(e.getSalary()*1.1));
	}
	
	@After
	public void test(){
		System.out.println("Employees with even numbers are:");
		ArrayList<Employee> list1 = es.get(e->e.getId()%2==0);
		for (Employee employee : list1) {
			System.out.println(employee);
		}
		
		System.out.println("Employees with salary less than 10000 include:");
		ArrayList<Employee> list2 = es.get(e->e.getSalary()<10000);
		for (Employee employee : list2) {
			System.out.println(employee);
		}
		
		System.out.println("Female employees older than 30 are:");
		ArrayList<Employee> list3 = es.get(e->e.getAge()>30 && e.getGender()=='female');
		for (Employee employee : list3) {
			System.out.println(employee);
		}
		
		System.out.println("Employees surnamed Zhang are:");
		ArrayList<Employee> list4 = es.get(e->e.getName().startsWith("Zhang"));
		for (Employee employee : list4) {
			System.out.println(employee);
		}
		
		System.out.println("All employees are:");
		ArrayList<Employee> list5 = es.get(e -> true);
		for (Employee employee : list5) {
			System.out.println(employee);
		}
		System.out.println();
	}
	
	
}

Question 7

Case:

1. Known student scores are as follows

full nameachievement
CEN Xiaocun59
Gu Tianluo82
Zha Zha Hui98
LAN Xiaoyue65
Tens of thousands of skin70

Create a set with student name as key and score as value and store data

2. Use lambda expressions to encapsulate the following functions into Function objects

(1) Save value in map < string, integer > to ArrayList < integer >

(2) Averages all elements in an ArrayList of Integer type

3. Use the Function object to find the average value of students

package com.atguigu.test07;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

public class Test07 {
	public static void main(String[] args) {
//		Encapsulate student names and grades into a map
		HashMap<String,Integer> map = new HashMap<String, Integer>();
        map.put("CEN Xiaocun", 59);
        map.put("Gu Tianluo", 82);
        map.put("Zha Zha Hui", 98);
        map.put("LAN Xiaoyue", 65);
        map.put("Tens of thousands of skin", 70);
        
//        Save value in map < string, integer > to ArrayList < integer >
        Function<Map<String,Integer>,ArrayList<Integer>> f1 = (m)->{
            ArrayList<Integer> list = new ArrayList<>();
            list.addAll(m.values());
            return list;
        };
        
//        Averages all elements in an ArrayList of Integer type
        Function<ArrayList<Integer>,Double> f2 = (list)->{
            double sum = 0;
            for (Integer i : list) {
                sum+=i;
            }
            return sum/list.size();
        };
        
        //Average score using Function
        Double avg = f1.andThen(f2).apply(map);
        System.out.println("The average student grade is:"+avg);
	}
}

Question 8

There are now two ArrayList collections that store the names of multiple members of the team,

List<String> one = new ArrayList<>();
		one.add("cool breeze");
		one.add("Chen Xuanfeng");
		one.add("Mei Chaofeng");
		one.add("Lu Chengfeng");
		one.add("Qu Lingfeng");
		one.add("Wu Mianfeng");
		one.add("Feng mofeng");
		one.add("Luo Yufeng");

		List<String> two = new ArrayList<>();
		two.add("Song Yuanqiao");
		two.add("Yu Lianzhou");
		two.add("Yu Daiyan");
		two.add("Zhang Songxi");
		two.add("Zhang Cuishan");
		two.add("Yin Litang");
		two.add("Zhang Shenggu");

Stream mode is required to perform the following steps:

  1. The first team only needs the name of the member whose name is three words;

  2. After the screening of the first team, only the first four people;

  3. The second team only needs the names of members surnamed Zhang;

  4. After the second team is screened, do not the first one;

  5. Merge the two teams into one team;

  6. Create a Student object by name; The Student type contains the name attribute

  7. Print Student object information for the entire team.

package com.atguigu.test08;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

public class Test08 {
	public static void main(String[] args) {
		List<String> one = new ArrayList<>();
		one.add("cool breeze");
		one.add("Chen Xuanfeng");
		one.add("Mei Chaofeng");
		one.add("Lu Chengfeng");
		one.add("Qu Lingfeng");
		one.add("Wu Mianfeng");
		one.add("Feng mofeng");
		one.add("Luo Yufeng");

		List<String> two = new ArrayList<>();
		two.add("Song Yuanqiao");
		two.add("Yu Lianzhou");
		two.add("Yu Daiyan");
		two.add("Zhang Songxi");
		two.add("Zhang Cuishan");
		two.add("Yin Litang");
		two.add("Zhang Shenggu");

		// The first team only needs the name of the member whose name is three words;
		// After the screening of the first team, only the first four people;
		Stream<String> streamOne = one.stream().filter(s -> s.length() == 3).limit(6);

		// The second team only needs the names of members surnamed Zhang;
		// After the second team is screened, do not the first one;
		Stream<String> streamTwo = two.stream().filter(s -> s.startsWith("Zhang")).skip(1);

		// Merge the two teams into one team;
		// Create a Student object by name;
		// Print Student object information for the entire team.
		Stream.concat(streamOne, streamTwo).map(Student::new).forEach(System.out::println);
	}
}

class Student {
	private String name;

	public Student() {
	}

	public Student(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	@Override
	public String toString() {
		return " Student {name='" + name + "'}";
	}
}

Question 9

Case:

The following are the top 10 global best films and Chinese best films rated by an unknown organization:

Global 1, Godfather 2, Shawshank Redemption 3, Schindler's list 4, Citizen Kane 5, Casablanca 6, godfather sequel 7, the seven Knights 8, Star Wars 9, American Beauty 10, leap over the madhouse

Chinese

1. Farewell my concubine 2. Making havoc in heaven 3. The devil is coming 4. Talking about a journey to the west 5. Living 6. Eating and drinking men and women 7. Infernal Affairs 8. Strange stories in the book of heaven 9. Nezha's mind 10. Sudden release of spring

1. Now save the movie names in the two lists into the two ArrayList sets in order

2. By stream

1) Print the top three film names in the global film ranking

2) Print the bottom 5 film names in the Chinese film ranking list

3) Pick out the top 5 in the two rankings and store them in a new collection

4) Define the movie Film class, create a Film object with the movie name name and save it to the collection. The Film type contains the movie name attribute

package com.atguigu.test09;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Test09 {
	public static void main(String[] args) {
		// Storing raw data into a collection
		ArrayList<String> global = new ArrayList<>();
		global.add("<Godfather");
		global.add("<Shawshank Redemption");
		global.add("<Schindler's list");
		global.add("<Citizen Kane");
		global.add("<Casablanca");
		global.add("<Godfather sequel");
		global.add("<Seven Warriors");
		global.add("<Star Wars");
		global.add("<American Beauty");
		global.add("<Leap over the madhouse");
		
		ArrayList<String> china = new ArrayList<>();
		china.add("<Farewell my concubine");
		china.add("<Making havoc in heaven");
		china.add("<Here comes the devil");
		china.add("<Dahua journey to the West");
		china.add("<Alive");
		china.add("<Men and women");
		china.add("<Infernal Affairs");
		china.add("<"The book of heaven"");
		china.add("<Nezha's mind");
		china.add("<"The sudden release of spring"");

		// 1) Print the top three film names in the global film ranking
		global.stream().limit(3).forEach(System.out::println);
		System.out.println();

		// 2) Print the bottom 5 film names in the Chinese film ranking list
		china.stream().skip(china.size() - 5).forEach(System.out::println);
		System.out.println();

		// 3) Pick out the top 5 in the two rankings and store them in a new collection
		List<String> list = Stream.concat(global.stream().limit(5), china.stream().limit(5))
				.collect(Collectors.toList());
		for (String string : list) {
			System.out.println(string);
		}
		System.out.println();

		// 4) Create a Film object with the movie name name for all movies and save it to the collection
		List<Film> filmList = Stream.concat(global.stream(), china.stream()).map(Film::new)
				.collect(Collectors.toList());
		for (Film film : filmList) {
			System.out.println(film);
		}
	}
}

class Film {
	private String name;

	public Film() {
	}

	public Film(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

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

	@Override
	public String toString() {
		return "Film [name=" + name + "]";
	}
	
}

Question 10

China has 34 provincial administrative regions, namely:

23 provinces:

Hebei, Shanxi, Jilin, Liaoning, Heilongjiang, Shaanxi, Gansu, Qinghai, Shandong, Fujian, Zhejiang, Taiwan, Henan, Hubei, Hunan, Jiangxi, Jiangsu, Anhui, Guangdong, Hainan, Sichuan, Guizhou and Yunnan.

4 municipalities directly under the Central Government:

Beijing, Tianjin, Shanghai and Chongqing.

5 autonomous regions:

Inner Mongolia Autonomous Region, Xinjiang Uygur Autonomous Region, [Xiahui autonomous region, Guangxi Zhuang Autonomous Region and Tibet Autonomous Region

2 Special Administrative Regions:

Hong Kong Special Administrative Region, Macao Special Administrative Region

Use stream:

1. Count the number of three word provinces

2. Count the number of provinces (East, West, North and South) whose names contain location nouns

3. Print the names of ordinary provinces (non autonomous regions, municipalities and special administrative regions) whose names contain location nouns

4. Extract all special provinces (autonomous regions, municipalities and special administrative regions) and put them into a new array

package com.atguigu.test10;

import java.util.Arrays;
import java.util.stream.Stream;

public class Test10 {
	public static void main(String[] args) {
		String[] provinces = { "Hebei Province", "Shanxi Province", "Jilin Province", "Liaoning Province", "Heilongjiang Province", "Shaanxi Province", "Gansu Province", "Qinghai Province", "Shandong Province", "Fujian Province", "Zhejiang Province", "Taiwan Province",
				"Henan Province", "Hubei province", "Hunan Province", "Jiangxi Province", "Jiangsu Province", "Anhui Province", "Guangdong Province", "Hainan ", "Sichuan Province", "Guizhou Province", "Yunnan Province", "Beijing", "Tianjin", "Shanghai", "Chongqing City",
				"Inner Mongolia Autonomous Region", "Xinjiang Uygur Autonomous Region", "Ningxia Hui Autonomous Region", "Guangxi Zhuang Autonomous Region", "Tibet Autonomous Region", "Hong Kong Special Administrative Region", "Macao Special Administrative Region" };

		// 1. Count the number of three word provinces
		long threeCount = Stream.of(provinces).filter(s -> s.length() == 3).count();
		System.out.println("Number of three word provinces:" + threeCount);

		// 2. Count the number of provinces (East, West, North and South) whose names contain location nouns
		long count = Stream.of(provinces)
				.filter(s -> s.contains("east") || s.contains("west") || s.contains("south") || s.contains("north")).count();
		System.out.println("The number of provinces (East, West, North and South) containing the noun of location:" + count);

		// 3. Print the names of ordinary provinces (non autonomous regions, municipalities and special administrative regions) whose names contain location nouns
		System.out.println("Common provinces that contain location nouns are:");
		Stream.of(provinces).filter(s -> s.contains("east") || s.contains("west") || s.contains("south") || s.contains("north"))
				.filter(s -> s.contains("province")).forEach(System.out::println);

		// 4. Extract all special provinces (autonomous regions, municipalities and special administrative regions) and put them into a new array
		String[] pros = Stream.of(provinces).filter(s -> !s.contains("province")).toArray(String[]::new);
		System.out.println("New array:" + Arrays.toString(pros));
	}
}

Topics: Java