A week's study

This week's lessons are: exceptions, collections, IO streams, multithreading.

abnormal

1. I personally understand that exceptions are abnormal events that occur in the process of running a program, which will end the running program.
2.Java exception handling: Java has the ability to handle exceptions. Java has five keywords to handle exceptions: try, catch, finally, throw, throws
try: It executes code that may produce exceptions
Catch: It is used to catch exceptions
finally: It's code that executes regardless of whether the program has an exception or not.
Throw: Automatically and manually throw exceptions
throws: Various exceptions that a declarative method might throw

public static void main(String[] args) {
        // TODO Auto-generated method stub
        // abnormal

        try {
            System.out.print("Please enter the first number.:");
            Scanner scanner = new Scanner(System.in);
            int a = scanner.nextInt();
            System.out.print("Please enter the first number.:");
            int b = scanner.nextInt();
            System.out.println(a / b);
        } catch (InputMismatchException exception) {
            System.out.println("Divisions and dividends must be positive");
        } catch (ArithmeticException exception) {
            System.out.println("The divisor cannot be zero");
        } catch (Exception e) {
            System.out.println("Other anomalies");
        } finally {
            System.out.println("Thank you for using.");
        }
    }
public static void main(String[] args) {
        // TODO Auto-generated method stub

        try {
            Scanner scanner = new Scanner(System.in);
            System.out.print("Please enter the course code.(1~3 Numbers between):");
            int a = scanner.nextInt();
            switch (a) {
            case 1:
                System.out.println("C#Programming "";
                break;
            case 2:
                System.out.println("C language");
                break;
            case 3:
                System.out.println("JAVA");
                break;
            default:
                System.out.println("Enter only 1~3 Numbers between");
                break;
            }
        } catch (InputMismatchException exception) {
            System.out.println("The number entered must be a number");
        } finally {
            System.out.println("Suggestions are welcome.");
        }
    }
public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            Person person = new Person();
            person.setAge(10);
            person.setSex("nothing");
            System.out.println("Create success");
        } catch (Exception e) {
            System.err.println(e.getMessage());
        } finally {
            System.out.println("Man is an advanced animal.");
        }
    }
}

class Person {
    private int age;
    private String sex;

    //
    public int getAge() {
        return age;
    }
    //throws Exception is an exception thrown pipeline
    public void setAge(int age) throws Exception {
        if (age > 0) {
            this.age = age;
        } else {
            throw new Exception("Age must be greater than 0"); //Exception object created
        }
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) throws Exception {
        if ("male".equals(sex) || "female".equals(sex)) {
            this.sex = sex;
        } else {
            throw new Exception("Must be male or female");
        }
    }

These are the exercises I did.

aggregate

Collection set: list, set
2.list: arrayList ,LinkedList
3.arrayList

arrayList

public class Demo01 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        List list = new ArrayList();
        list.add(new Dog("Strong and strong", 12));
        list.add(new Dog("Ball ball", 12));
        list.add(new Dog("Xi Xi", 12));
        list.add(1, new Dog("calmly", 11));
        Dog dog2 = new Dog("greatly", 13);
        list.add(dog2);
        // delete
        // E remove(int index)
        // Remove elements from this list at specified locations.
        // boolean remove(Object o)
        // Remove the specified element that appears for the first time in this list.
        list.remove(0);
        list.remove(dog2);
        // list.clear(); // remove all
        // query
        list.set(1, new Dog("Lily", 12));
        for (int i = 0; i < list.size(); i++) {
            // get is to retrieve content from an index location
            Dog dog = (Dog) list.get(i);
            System.out.println(dog.toString());
        }
    }
}

LinkedList

public class Demo01 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        LinkedList list = new LinkedList();// A parent reference points to a child class object
        // create object
        Dog pingping = new Dog("Average", 2);
        Dog tutu = new Dog("Bunny Rabbit", 2);
        Dog tu2 = new Dog("Tutu", 2);
        // Add to the collection
        list.add(pingping);
            list.addFirst(tutu);
        list.addLast(tu2);
        // Get the first element
        System.out.println(list.getFirst().toString());
        System.out.println(list.getLast().toString());
        // Delete the first
        list.removeFirst();
        list.removeLast();
        System.out.println("~~~~~~~~~~~~");
        for (int i = 0; i < list.size(); i++) {
            Dog dog = (Dog) list.get(i);
            System.out.println(dog.toString());
        }
    }
}

4.set:hashset

hashset

public class Demo04 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Set<Integer> set = new HashSet<Integer>();
        Random random = new Random();
        while (set.size() <= 10) {
            set.add(random.nextInt(20) + 1);
        }
        for (Integer integer : set) {
            System.out.println(integer);
        }
    }
}
public class Demo05 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //Remove duplicate characters
        Scanner scanner = new Scanner(System.in);
        System.out.print("Please enter a character:");
        String aString = scanner.nextLine();
        System.out.println(aString);
        HashSet<Character> hs = new HashSet<Character>();
        char[] arr = aString.toCharArray();
        for (char c : arr) {
            hs.add(c);
        }
        for (Character ch : hs) {
            System.out.print(ch);
        }
    }
}

5. generic

Generics allow you to limit the data processing type of a collection when writing it

6.Map

Map: Mapping keys to objects of value, a mapping cannot contain duplicate keys; each key can only map to a value at most

HashMap

public static void main(String[] args) {
        // TODO Auto-generated method stub
        Map<Character, Integer> map = new HashMap();
        Scanner scanner = new Scanner(System.in);
        System.out.print("Please enter a string:");
        String a = scanner.next();
        char[] chars = a.toCharArray();
        for (char c : chars) {
            if (map.containsKey(c)) {
                map.put(c, map.get(c) + 1);
            } else {
                map.put(c, 1);
            }
        }
        for (Character character : map.keySet()) {
            System.out.println(character + ":" + map.get(character));
        }
    }

7. traversal

list traversal can be either for loop or foreach
set can only be used foreach

8. iterator

public static void main(String[] args) {
        // TODO Auto-generated method stub
        Map<String, String> map = new HashMap<String, String>();
        // put method is added if there is no corresponding key value in the set, and modified if there is one.
        map.put("YL", "yl");
        map.put("LY", "ly");
        map.put("XY", "xy");
        /*
         * //The first iterator // takes all keys and stores them in the set set set set; Set < String > set = map. keySet ();
         * //set Iterator < String > iterator = set. iterator ();
         * //First, determine if there is the next element in the set set set; // If there is, get the next element; while (iterator.hasNext()){
         * //next:Get a reference to the object pointed by the current pointer, and after that, move the pointer one bit backward; String iString=
         * iterator.next(); System.out.println(iString + "\t" +
         * map.get(iString)); }
         */

        // The second iterator
        Set<Map.Entry<String, String>> set2 = map.entrySet();
        for (Map.Entry<String, String> entry : set2) {
            System.out.println(entry);
        }
    }

IO flow

1.file class: the specific location of the file in the system
2. Create files and folders

public static void main(String[] args) {
        // TODO Auto-generated method stub
        // Demo01();
        // Demo02();
        File file = new File("E:\\JAVA\\New folder");
        if (file.mkdirs()) {
            System.out.println("Create success");
        } else {
            System.out.println("Create failure");
        }
    }

    private static void Demo02() {
        File file = new File("E:\\JAVA\\New folder\\abd");
        if (file.mkdir()) {
            System.out.println("Create success");
        } else {
            System.out.println("Create failure");
        }
    }

    // Create empty files
    private static void Demo01() {
        File file = new File("E:\\JAVA\\New folder\\abd.txt");
        try {
            // file.createNewFile();
            if (file.createNewFile()) {
                System.out.println("Create success");
            } else {
                System.out.println("Create failure");
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

3. Rename and delete

public static void main(String[] args) {
        // Demo01();
        File newfile = new File("E:\\JAVA\\New folder\\abd2");
        if (newfile.delete()) {
            System.out.println("Delete successful");
        }
    }

    // modify
    private static void Demo01() {
        File file = new File("E:\\JAVA\\New folder\\abd");
        // New path
        File newfile = new File("E:\\JAVA\\New folder\\abd2");
        if (file.renameTo(newfile)) {
            System.out.println("Modified success");
        } else {
            System.out.println("Modification failed");
        }
    }

io flow

1.io stream: The way Java reads and writes (transfers) data through the stream
2. Byte Stream: Any data can be manipulated
3. Character Stream: Used to manipulate pure character files

Byte stream

public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        // Create an input stream
        FileInputStream fileInputStream = new FileInputStream(
                "E:\\JAVA\\New folder\\Love in my life.flac");
        // 2. Create an output stream
        FileOutputStream fStream = new FileOutputStream("E:\\JAVA\\New folder\\Love in Life 2.flac");
        // 3. Read and write
        int b;
        while ((b = fileInputStream.read()) != -1) {
            fStream.write(b);
        }
        fileInputStream.close();
        fStream.close();
    }

Character stream

public static void main(String[] args) {
        // TODO Auto-generated method stub
        FileReader fileReader = null;
        FileWriter fileWriter = null;
        try {
            fileReader = new FileReader("E:\\JAVA\\IO flow\\love you.txt");
            fileWriter = new FileWriter("E:\\JAVA\\IO flow\\Love you and love you.txt");
            int c;
            while ((c = fileReader.read()) != -1) {
                fileWriter.write(c);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                fileReader.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                fileWriter.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
public static void main(String[] args) {
        // TODO Auto-generated method stub
        BufferedReader bf = null;
        BufferedWriter bw = null;
        try {
            bf = new BufferedReader(new FileReader("E:\\JAVA\\IO flow\\abc.txt"));
            String line = null;
            StringBuffer stringBuffer = new StringBuffer();
            while ((line = bf.readLine()) != null) {
                stringBuffer.append(line);
            }
            System.out.println("Before replacement:" + stringBuffer);
            bw = new BufferedWriter(new FileWriter("E:\\JAVA\\IO flow\\abc.txt"));
            // Replacement character
            String string = stringBuffer.toString().replace("name", "XL").replace("type", "Siberian Husky").replace("master",
                    "AL");
            bw.write(string);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            try {
                bf.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                bw.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

Multithreading

1. Multithreading: Multiple Paths of Program Execution
2. Multithread concurrency: It can improve the efficiency of program execution and accomplish multiple tasks at the same time.
3. Multithread Running: Multiple Programs Running at the Same Time
4. Implementation of multithreading: 1. Subclasses inherit threads and override run methods. When the start method is executed, the run method of the subclass is executed directly. 2. Implementing the runnable interface

public static void main(String[] args) {
        // TODO Auto-generated method stub
        Mythread mythread = new Mythread();
        Mythread mythread2 = new Mythread();
        mythread.setName("Hello,From thread" + mythread);
        mythread.start();
        mythread2.setName("Hello,From thread" + mythread2);
        mythread2.start();
    }

}

class Mythread extends Thread {
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println(Thread.currentThread().getName() + ":" + i);
        }
    }
}

Sleep thread

public static void main(String[] args) {
        // TODO Auto-generated method stub
        // DemoA();
        for (int i = 10; i > 0; i--) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("The enemy also has:" + i + "S Arrive at the battlefield");
        }
        System.out.println("The whole army attacked.");
    }

    // ********************************************************************
    private static void DemoA() {
        new Thread() {
            public void run() {
                for (int i = 0; i < 10; i++) {
                    System.out.println(Thread.currentThread().getName() + ": " + i);
                    try {
                        Thread.sleep(1500);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }.start();
        new Thread() {
            public void run() {
                for (int i = 0; i < 10; i++) {
                    System.out.println(Thread.currentThread().getName() + ": " + i);
                    try {
                        Thread.sleep(1500);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }
}

thread priority

public static void main(String[] args) {
        // TODO Auto-generated method stub
        Thread thread = new Thread(new MyThread2(), "thread A");
        Thread thread2 = new Thread(new MyThread2(), "thread B");
        // Setting Thread Priority
        thread.setPriority(thread.MAX_PRIORITY);
        thread2.setPriority(thread.MIN_PRIORITY);
        thread.start();
        thread2.start();
        System.out.println(thread.getPriority());
        System.out.println(thread2.getPriority());
    }

}

class MyThread2 implements Runnable {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + "~~~~~~" + i);
        }
    }

}

Interface Implementation Thread

public static void main(String[] args) {
        // TODO Auto-generated method stub
        // Create Thread Objects
        MyRunnable myRunnable = new MyRunnable();
        // Open thread
        Thread thread = new Thread(myRunnable);
        Thread thread2 = new Thread(myRunnable);
        thread.start();
        thread2.start();

    }
}

class MyRunnable implements Runnable {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + ":" + i);
        }
    }
}

Multithread Execution State

public static void main(String[] args) {
        // TODO Auto-generated method stub
        Thread thread = new Thread(new MyThread3());
        System.out.println("Threads have been created");
        thread.start();
        System.out.println("Thread ready");
    }
}

class MyThread3 implements Runnable {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println("The program is running");
        try {
            System.out.println("Immediately into dormancy");
            Thread.sleep(1000);
            System.out.println("After a brief hibernation");
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Thread comity

public static void main(String[] args) {
        // TODO Auto-generated method stub
        Thread thread = new Thread(new Mythread5(), "thread A");
        Thread thread2 = new Thread(new Mythread5(), "thread B");
        thread.start();
        thread2.start();
    }

}

class MyThread5 implements Runnable {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + "Running");
            if (i == 3) {
                System.out.println("Thread comity");
                Thread.yield();
            }
        }
    }

Multithread Exercise Questions

public static void main(String[] args) {
        // TODO Auto-generated method stub
        Thread thread = new Thread(new MyThread4());
        thread.setPriority(10);
        thread.start();
        for (int i = 1; i < 50; i++) {
            System.out.println("Ordinary number:" + i + "Patient No. 1 is seeing a doctor");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (i == 10) {
                try {
                    thread.join();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }

}

class MyThread4 implements Runnable {
    // Special request number
    @Override
    public void run() {
        // TODO Auto-generated method stub
        for (int i = 1; i < 11; i++) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("Special request number:" + i + "Patient No. 1 is seeing a doctor!");
        }
    }
}
//These are the summaries of the week.

Keywords: Java Programming C

Added by hannnndy on Fri, 17 May 2019 16:45:28 +0300