Notes - Advanced Java Foundation to Face Difficulties 3

Posted by Nilpez on Thu, 23 May 2019 20:40:41 +0200

Statistical strings for each different character

import java.util.*;
//Statistics of the number of words per character in a string
public class StringDemo{
    public static void main(String[] args){
    Scanner aScanner = new Scanner(System.in);
    //Let the user enter a string
    System.out.println("Please enter the statement you want to count.");
    String aString = aScanner.next();
    //To count each character, you need to convert the string into a character. You can call the string method toCharArray.
    char[] aCharArray = aString.toCharArray();
    //Create a HashMap collection to store keys and values
    HashMap<Character,Integer> aHashMap = new HashMap<>();
    //Traversing character arrays
    for(Character key:aCharArray){
    //Take aChar as the key, first determine if there is a key in the collection, then add value plus one, if not, add keys into it.
    if(aHashMap.containsKey(key)){
        Integer value =aHashMap.get(key);
        value++;
        //Later values replace the previous values, and the put method adds values.
        aHashMap.put(key,value);
    }else{
        //No additions
        aHashMap.put(key,1);
    
    }
    }
    //Store key s in Set collections and traverse them
    Set<Character> aSet = aHashMap.keySet();
    //Traversing aHashMap
    for(Character key : aSet){
        Integer value = aHashMap.get(key);
        System.out.println(key+"="+value);
    }
    
    
    }
}

New features of JDK9:

List interface, Set interface and Map interface add a static method of, which can add multiple elements to the collection at one time.

Prerequisites for use: When the number of elements stored in the collection has been determined, it will not be changed. That is to say, after adding elements, it will not be possible to add elements using put method.

Matters needing attention:

  1. The of method is only applicable to List interface, Set interface and Map interface, but not to the implementation class of interface.

  2. The return value of the of method is a set that cannot be changed

  3. Set interface and Map interface are suitable for calling of method. They can't store duplicate elements, otherwise they will throw exceptions.

import java.util.*;
public class JDK9Demo{
    public static void main(String[] args){
    List<String> list = List.of("a","b","c","d","a");//Repeatable elements
    System.out.println(list);
    
    Set<String> set = Set.of("a","b","c");//No duplicate elements allowed
    System.out.println(set);
    
    Map<String,Integer> map = Map.of("Zhang San",18,"Li Si",17,"Wang Wu",16,"Zhao San",18);//No duplication of elements, no duplication of keys, no duplication of values
    System.out.println(map);
    }
}

Debug tracking

Debug debugger

You can let the code execute line by line, see the process of code execution, and de bug bugs in the program

f8: Line-by-line execution program f7: Enter shift+f8 jump-out method

f9: Jump to the next breakpoint ctrl +f2 to exit debug mode and stop the program

Console: Switch to console

Landlord Fighting Case List

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

public class DouDiZhu {
    public static void main(String[] args){
        //Index represented by Integer, and size represented by String
        HashMap<Integer,String> poker = new HashMap<>();
        //Create a List collection, store the index of the card, and sort the index
        ArrayList<Integer> pokerIndex = new ArrayList<>();
        //Define two sets to store the color and the serial number of the brand
        List<String> colors = List.of("♠","♥","♣","♦");
        List<String> numbers = List.of("2","A","K","Q","J","10","9","8","7","6","5","4","3");
        //Store Kings and Kings in a collection
        int index = 0;
        poker.put(index,"king");
        pokerIndex.add(0);
        index++;
        poker.put(index,"Xiao Wang");
        pokerIndex.add(index);
        index++;
        //0 index represents the king, 1 index represents Xiaowang, and so on, you can sort the index later, that is, sort the cards.
        for(String number : numbers){
            for(String color :colors){
                String str = color+number;
                poker.put(index,str);
                //The index of the card should also be added, because it represents the size of the card.
                pokerIndex.add(index);
                index++;
            }
        }
        //Use the method shuffle() in Collections;
        Collections.shuffle(pokerIndex);
        ArrayList<Integer> p1 = new ArrayList<>();
        ArrayList<Integer> p2 = new ArrayList<>();
        ArrayList<Integer> p3 = new ArrayList<>();
        ArrayList<Integer> p4 = new ArrayList<>();
        for(int i=0;i <pokerIndex.size();i++){
            //Turn to Integer type first, or you will add failures
            Integer in = pokerIndex.get(i);
            if(i>=51){
                p4.add(in);
            }else if(i%3==0){
                p1.add(in);
            }else if(i%3==1){
                p2.add(in);
            }else if(i%3==2){
                p3.add(in);
            }

        }
        //Sort the cards that have been divided
        Collections.sort(p1);
        Collections.sort(p2);
        Collections.sort(p3);
        Collections.sort(p4);
        lookPoker("Lau Andy",poker,p1);
        lookPoker("Zhou Runfa",poker,p2);
        lookPoker("Stephen Chow",poker,p3);
        lookPoker("A hand",poker,p4);
    }
    public static void lookPoker(String name,HashMap<Integer,String> poker,ArrayList<Integer> list){
            System.out.print(name+": ");
            for(Integer key : list){
                //Getting values by index
                String value = poker.get(key);
                System.out.print(value+" ");
            }
            System.out.println();
    }
}
abnormal

Throwable has two subclasses Exception and Error

Error: Serious errors, errors that cannot be handled, can only be avoided, like terminal illness

Exception: Represents exceptions. After exceptions occur, programmers can correct them by code, so that the program can continue to run. It is necessary to deal with them.

The throw keyword can throw the specified exception object in the specified method

/*
throw Keyword
 Effect:
    You can use the throw keyword to throw the specified exception in the specified method
    Use format:
        throw  new xxxException("The cause of the abnormality.
    Be careful:
        1.throw Keyword must be written inside the method
        2.throw The new object behind the keyword must be a subclass object of Exception or Exception
        3.throw Keyword throws the specified exception object, which we have to deal with
            throw The keyword is followed by a RuntimeException or a subclass object of RuntimeException, which we can leave untreated by default to the jvm.
            throw The compiler exception is created behind the keyword, and we have to deal with it.
*/  
public class ThrowDemo{

    public static void main(String[] args){
        int[] arr= new int[3];
        int e = getElement(arr,-2);
        System.out.println(e);
        //Throws specified exceptions
        //Exception in thread "main" java.lang.NullPointerException: The passed array is empty
        //at ThrowDemo.getElement(ThrowDemo.java:24)
        //at ThrowDemo.main(ThrowDemo.java:18)
    }
    //If the passed parameters are not valid, then we must use an exception thrown to inform the caller of the method that there is a problem with the passed parameters.
    public static int getElement(int[] arr,int index){
        
    if(index<0 || index>arr.length-1){
        throw new ArrayIndexOutOfBoundsException("The index passed cannot exceed or fall below the scope");
    }
    if(arr == null){
        //If it is null, specify it as a null pointer exception
        throw new NullPointerException("The passed array is empty");
    }
    int i = arr[index];
    return i;
    }   
}

Non-empty Judgment of Objects

Objects.requireNonNull(); can determine whether an object is null

import java.util.Objects;
public class ThrowDemo{

    public static void main(String[] args){
        method("Clouds think of clothes and flowers");//Passing null returns a NullPointerException exception
    }
    public static void method(Object obj){
        Object objects=Objects.requireNonNull(obj);
        System.out.println(objects);
    }
}

The first way of throws keyword _exception handling

/*
    throws Keyword: When an exception object is thrown inside a method, we have to deal with the exception object. We can use the thorws keyword to deal with the exception object and throw the exception object declaration to the caller of the method.

*/
import java.io.FileNotFoundException;
public class ThrowsDemo{
    public static void main(String[] args)throws FileNotFoundException{
        readFile("d:\\a.txt");
    }
    public static void readFile(String fileName)throws FileNotFoundException{
    //Throw an exception if the file passed in is incorrect
    if(!fileName.equals("c:\\a.txt")){
        throw new FileNotFoundException("The file path passed is incorrect. Please redistribute it.");
    }
    
    System.out.println("Successful delivery path");
    }
}

The second way to handle try_catch exceptions

Capture exception grammar format
try{
    Write code that may have exceptions
 } catch (exception type e used to receive exception information thrown in try){
    Handling exception code
}
....
 catch(){}

Be careful:
There may be multiple exception objects thrown in try, so you can use multiple catch es for a long time to handle these exception objects
 If an exception is generated in try, the exception handling logic in catch is executed
import java.io.FileNotFoundException;
public class ThrowsDemo1{
    public static void main(String[] args){
        try{
            readFile("d:\\a.txt");
        }catch(FileNotFoundException e){
            System.out.println("Wrong file passed");
        }
        System.out.println("Follow up code");
    }
    public static void readFile(String fileName)throws FileNotFoundException{
    //Throw an exception if the file passed in is incorrect
    if(!fileName.equals("c:\\a.txt")){
        throw new FileNotFoundException("The file path passed is incorrect. Please redistribute it.");
    }
    System.out.println("There is no problem with the path.");
}
}

Three methods of exception handling in Throwable class

getMessage(): A brief description

toString(): Detailed message string

printStackTrace(): Printed exception information is the most comprehensive

Word Abnormal Character Class
public class Fu{
    public void show1()throws NullPointerException,ClassCastException{}
    public void show2()throws IndexOutOfBoundsException{}
    public void show3()throws IndexOutOfBoundsException{}
    


class Zi extens Fu{
//The subclass overrides the parent by throwing the same exception as the parent
public void show1()throws NullPointerException,ClassCastException{}
//When a subclass overrides a parent method, it throws a subclass with a parent exception
    public void show2()throws ArrayIndexIndexOutOfBoundsException{}
//When subclasses override parent methods, no exception is thrown
    public void show3(){}
//The parent class does not throw an exception, nor can the child class throw an exception. If there is an exception, try catch is needed to handle the exception.

Custom exception

//Customize a registration exception
//We need a method to construct empty parameters and a method to construct abnormal information.
//Inheriting Exception // then the custom exception class is a compiler exception, which requires throws or try...catch processing
//The inheritance is Runtime Exception, so the exception is handed over to the virtual machine in disorder.

public class RegisterException extends Exception{
    public RegisterException(){}
    public RegisterException(String message){
    super(message);
    }

}
import java.util.*;

//Use custom exception classes
public class ExceptionDemo{
    //Define a collection to store names
    public static void main(String[] args){
    ArrayList<String> list = new ArrayList<>();
    list.add("James");
    list.add("Kobe");
    list.add("Jordan");
    list.add("Dirk Nowitzki");
    list.add("Duncan");
    System.out.println(list);
    //Let users enter nicknames
    Scanner sc = new Scanner(System.in);
    System.out.println("Please enter your nickname");
    String nicheng = sc.next();
    //Add a name to it, add success if it does not exist, and return a registration exception if it does.
    for(String name : list){
        //Using string equals to determine whether an element exists in a collection will return a boolean
        //To be true, it means that the nickname already exists and a registration exception needs to be returned.
        if(name.equals(nicheng)){
            try{
                throw new RegisterException("Pro, the nickname has been registered.");
            }catch(RegisterException e){
                e.printStackTrace();
                return;//Once an anomaly is released, the method is immediately terminated.
            }               
        }
        //After traversal, if no exception occurs, the nickname can be created
        
    }
        list.add(nicheng);
        System.out.println("Congratulations on your successful registration");
    }
}
Multithreading
public class ThreadDemo{
    public static void main(String[] args){
    MyThread mt = new MyThread();
    //Execute the start method, open the thread, and execute the run method
  //If mt.run(); is used, the program will execute in heap memory, which is not multi-run, but single-threaded.
  //Every time you use start(); a new thread is created to execute the run method in the stack space. The advantage of multiple threads is that threads do not affect each other and cup executes which thread it likes.
    mt.start();
    for(int i= 0;i<10;i++){
        System.out.println("main thread"+i);
    }
    }
}
public class MyThread extends Thread{
    //Rewriting run Method
    public void run(){
        for(int i=0;i<10;i++){
        System.out.println("run thread"+i);
        }
    }
}

Common methods of Thread classes

Method of getting thread name

1. Use the method getName in the Thread class
    String getName() returns the name of the thread, which calls me and I return its name.
2. You can first get the thread currently executing, and then use the method getName() in the thread to get the name of the thread.
public class MyThread1 extends Thread{
    public void run(){
        /*The first way to get a name
        String name=getName();
        System.out.println(name);*/
       // The second way to get a name
        //Get the current thread first (currentThread is a static method that can get threads directly by class name)
        Thread t = Thread.currentThread();//This method returns the current thread
        //Getting names through threads
        String naem =t.getName();
        System.out.println(name);
    }
}
public class ThreadName{
    public static void main(String[] args){
        MyThread1 mt = new MyThread1();
        mt.start();
    }
}

Set the thread name

One is through the setName method, and the other is through the construction method.

public class ThreadName{
    public static void main(String[] args){
        MyThread1 mt = new MyThread1();
        mt.setName("Cockroach");
        mt.start();
        new MyThread1("Prosperous wealth").start();
    }
}
public class MyThread1 extends Thread{
    public MyThread1(){}
    public MyThread1(String name){
        super(name);
    }
    public void run(){
    /*The first way to get a name
        String name=getName();
        System.out.println(name);*/
       // The second way to get a name
        //Get the current thread first
        Thread t = Thread.currentThread();
        //Getting names through threads
        String name =t.getName();
        System.out.println(name);
    }
}

sleep method

Is a static method that can be invoked directly with the class name to allow the current thread to sleep for a specified time

The Second Way to Create Multithread Programs Implementing Runnable Interface

Implementation steps:

1. Create an implementation class of Runnable interface

  1. Rewrite the run method of the Runnable interface in the implementation class and set the thread task

  2. Create an Implementation Class Object for Runnable Interface

  3. Create Thread class object, pass Runnable interface implementation class object in construction method

  4. Call the start method of the Thread class to open the thread

    public class RunnableImp implements Runnable{
     public void run(){  
         for(int i=0;i<10;i++){
             //Get the current thread, and then get the thread name
         System.out.println(Thread.currentThread().getName()+"--"+i);
         }
     }
    }
    public class RunnableDemo {
     public static void main(String[] args){
         //Creating Runnable Interface to Implement Class Objects
         RunnableImp run = new RunnableImp();
         //There is a constructor in Thread that can be passed as a parameter via the Runnable interface
         new Thread(run).start();
    
         for(int i=0;i<10;i++){
                 //To get the thread of the main method, you can only get the thread name in the following way
                 System.out.println(Thread.currentThread().getName()+"--"+i);
             }
     }
    }

Topics: Java P4 jvm