20145317 Peng Yao "Java program Design" 5th Week study Summary

Source: Internet
Author: User

20145317 Peng Yao "Java program Design" The 5th Week study summary textbook Learning content Summary
    • Eighth Chapter
    • 8.1 Syntax and inheritance schema
    • package CH5;/** * Created by Administrator on 2016/3/29. */import java.util.Scanner;public class Average { public static void main(String[] args) { Scanner console = new Scanner(System.in); double sum = 0; int count = 0; while(true){ int number = console.nextInt(); if(number ==0){ break; } sum += number; count++; } System.out.printf("平均 %.2f%n",sum / count); }}
    • All errors in Java are packaged as objects, and if you want, you can try to catch the object that represents the error and then do some processing
    • package CH5;/** * Created by Administrator on 2016/3/29. */import java.util.*;public class Average2 { public static void main(String[] args) { try{ Scanner console = new Scanner(System.in); double sum = 0; int count = 0; while (true){ int number = console.nextInt(); if(number ==0){ break; } sum += number; count++; } System.out.printf("平均 %.2f%n", sum/count); }catch (InputMismatchException ex){ System.out.println("必须输入整数"); } }}
    • Sometimes errors can be attempted after the capture process, to try to recover the program's normal execution process:
    • package CH5;/** * Created by Administrator on 2016/3/29. */import java.util.*;public class Average3 { public static void main(String[] args) { Scanner console = new Scanner(System.in); double sum = 0; int count = 0; while (true) { try { int number = console.nextInt(); if (number == 0) { break; } sum += number; count++; } catch (InputMismatchException ex) { System.out.printf("略过非整数输入:%s%n", console.next()); } } System.out.printf("平均 %.2f%n", sum/count); }}


Errors are wrapped as objects that are all java.lang.Throwable, so the design Error object inherits from the class, and Throwable defines the method of getting the error message, the stack trace, etc. It has two sub-categories: Java.lang.Error and Java.lang.Exception.
Error and its subclass instance represent a serious system error, when a serious system error occurs, the Java application itself is unable to reply, when the Error object is thrown, it basically does not have to be processed, let it propagate to the JVM, or leave the log information at most.

package CH5;/** * Created by Administrator on 2016/3/29. */import java.util.Scanner;public class Average4 {    public static void main(String[] args) {        double sum = 0;        int count = 0;        while(true){            int number = nextInt();            if(number ==0){                break;            }            sum += number;            count++;        }        System.out.printf("平均 %.2f%n",sum / count);    }    static Scanner console = new Scanner(System.in);    static int nextInt(){        String input = console.next();        while(!input.matches("\\d*")){            System.out.println("请输入数字");            input = console.next();        }        return Integer.parseInt(input);    }}

If the parent exception object is caught before the subclass exception object, the chunk of the catch subclass exception object will never be executed, and the compiler will check for this error.
Java design that the non-inspected exception is a bug caused by improper program design, the exception should be automatically spread out, should not use try, catch to attempt processing, but should improve the program logic to avoid throwing errors.

package CH5;/** * Created by Administrator on 2016/3/29. */import java.io.*;import java.util.Scanner;public class FileUtil {    public static String readFile(String name) throws FileNotFoundException{        StringBuilder text = new StringBuilder();        try{            Scanner console = new Scanner (new FileInputStream(name));            while(console.hasNext()){                text.append(console.nextLine())                        .append(‘\n‘);            }        }catch(FileNotFoundException ex){            ex.printStackTrace();            throw ex;        }        return text.toString();    }}

Java is the only language that uses exceptions, which has two purposes: one is documentation, and the other is to provide compiler information.
The simplest way to view the stack trace is to call the Printstacktrace () of the exception object directly.

package CH5;/** * Created by Administrator on 2016/3/29. */public class StackTraceDemo {    public static void main(String[] args) {        try{            c();        }catch(NullPointerException ex){            ex.printStackTrace();        }    }    static void c(){        b();    }    static void b(){        a();    }    static String a(){        String text = null;        return text.toUpperCase();    }}

Make good use of stack tracing, provided that the program code does not have pocketed behavior, improper handling of the exception, or incorrect information displayed.

package CH5;/** * Created by Administrator on 2016/3/29. */public class StackTraceDemo2 {    public static void main(String[] args) {        try{            c();        }catch(NullPointerException ex){            ex.printStackTrace();        }    }    static void c(){        try{            b();        }catch(NullPointerException ex) {            ex.printStackTrace();            throw ex;        }    }    static void b(){        a();    }    static String a(){        String text = null;        return text.toUpperCase();    }}

package CH5;/** * Created by Administrator on 2016/3/29. */public class StackTraceDemo3 {    public static void main(String[] args) {        try{            c();        }catch(NullPointerException ex){            ex.printStackTrace();        }    }    static void c(){        try{            b();        }catch(NullPointerException ex) {            ex.printStackTrace();            Throwable t = ex.fillInStackTrace();            throw(NullPointerException) t;        }    }    static void b(){        a();    }    static String a(){        String text = null;        return text.toUpperCase();    }}


8.2 Exceptions and resource management
If there is an exception in the try block, if a finally chunk is written, then the finally block is bound to be executed. If the process in which the program is written returns first, and there are finally chunks, the finally chunk is executed before the value is returned.

  Package ch5;/** * Created by Administrator on 2016/3/29. */import Java.io.*;import java.util.scanner;public cl trycatchfinally {public static string ReadFile (string name) throws filenotfoundexception{StringBuilder Tex        t = new StringBuilder ();        Scanner console = null;            try{console = new Scanner (new FileInputStream (name));            while (Console.hasnext ()) {Text.append (Console.nextline ()). append (' \ n ');            }}finally{if (console!=null) {console.close ();    }} return text.tostring (); }}
package CH5;/** * Created by Administrator on 2016/3/29. */public class FinallyDemo {    public static void main(String[] args) {        System.out.println(test(true));    }    static int test(boolean flag){        try{            if(flag){                return 1;            }        }finally{            System.out.println("finally...");        }    }return 0;}

After the JDK, a new attempt was made to close the resource syntax, and the object to attempt to automatically close the resource is written in parentheses after the try.

package CH5;/** * Created by Administrator on 2016/3/29. */import java.io.FileInputStream;import java.io.FileNotFoundException;import java.util.Scanner;public class FileUtil2 {    public static String readFile(String name) throws FileNotFoundException {        StringBuilder text = new StringBuilder();        try (Scanner console = new Scanner(new FileInputStream(name))) {            while (console.hasNext()) {                text.append(console.nextLine())                        .append(‘\n‘);            }        }        return text.toString();    }}

The JDK tries to close the resource syntax of the applied object and must manipulate the Java.lang.AutoCloseable interface, which is the JDK7 new interface. Attempting to close resource syntax can also close more than two object resources at the same time, as long as the middle is separated by semicolons. In the parentheses of the try, the sooner the object resource is written, the sooner it is closed.

package CH5;/** * Created by Administrator on 2016/3/29. */public class AutoClosableDemo {    public static void main(String[] args) {        try(Resource res = new Resource()){            res.doSome();        }catch(Exception ex){            ex.printStackTrace();        }    }}class Resource implements AutoCloseable{    void doSome(){        System.out.println("做一些事");    }    @Override    public void close() throws Exception{        System.out.println("资源被关闭");    }}
Nineth Chapter

9.1
· Javase provides APIs to meet a variety of requirements, and the behavior of collecting objects is defined in the java.collection, which can both collect objects and expel objects.
• If your phone has an index order, you can use an array.
· List is a collection that collects objects and preserves the order of objects in the cell by index

  Import Java.util.arrays;public class Arraylist<e> {private object[] elems;       private int Next;    public ArrayList (int capacity) {Elems = new object[capacity];    } public ArrayList () {this (16);        } public void Add (e e) {if (next = = elems.length) {elems = arrays.copyof (Elems, elems.length * 2);    } elems[next++] = e;    Public E get (int index) {return (E) Elems[index];    } public int size () {return next; }}

· Arraylistarraylist characteristics: Arrays in memory will be continuous linear space, according to the index random access speed, if the operation of such requirements, such as sorting, you can use ArrayList, can get better speed performance.
· LinkedList uses the link structure when manipulating the list interface.
• If there are identical objects in the collection process, the collection is no longer repeated, and if there is such a requirement, the operands of the set interface can be used.
· The concept of hashset is to open space in memory, where each space will have a hash code. The queue inherits from collection, so it also has the collection add (), remove (), Element () methods, but the queue defines its own offer (), poll () and peek (), etc. One of the main differences is that when a method such as add (), remove (), element () fails, an exception is thrown, and a specific value is returned when a method operation such as offer (), poll () and Peek () fails.
• If the object has an operation queue and is intended to be used in queues and the queue length is limited, it is generally advisable to use the offer (), poll (), and Peek () methods. LinkedList not only operates the list interface, but also operates the queue behavior, so the LinkedList can be used as a queue.

import java.util.*;interface Request {    void execute();}public class RequestQueue {    public static void main(String[] args) {        Queue requests = new LinkedList();        offerRequestTo(requests);        process(requests);    }    static void offerRequestTo(Queue requests) {        // 模擬將請求加入佇列        for (int i = 1; i < 6; i++) {            Request request = new Request() {                public void execute() {                    System.out.printf("處理資料 %f%n", Math.random());                }            };            requests.offer(request);        }    }    // 處理佇列中的請求    static void process(Queue requests) {        while(requests.peek() != null) {            Request request = (Request) requests.poll();            request.execute();        }    }}

• Use Arraydeque to operate a stack with limited capacity:

  Import java.util.*;import static Java.lang.system.out;public class Stack {private Deque elems = new Arrayde    Que ();        private int capacity;    public Stack (int capacity) {this.capacity = capacity;        The public boolean push (Object elem) {if (Isfull ()) {return false;    } return Elems.offerlast (Elem);    } private Boolean Isfull () {return elems.size () + 1 > capacity;    } public Object Pop () {return elems.polllast ();    } public Object Peek () {return elems.peeklast ();    } public int size () {return elems.size ();        public static void Main (string[] args) {Stack stack = new Stack (5);        Stack.push ("Justin");        Stack.push ("Monica");        Stack.push ("Irene");        Out.println (Stack.pop ());        Out.println (Stack.pop ());    Out.println (Stack.pop ()); }}

• The front and tail of the queue are manipulated, the object is added to the front end and the object is fetched, the object is added to the end and the object is fetched, and the sub-interface of the deque defines such behavior Java.util.ArrayDeque operates the Deque interface and can use Arraydeque to manipulate a stack with limited capacity. Generic Syntax: The class name has corner brackets <>, which means that this class supports generics. The object that is actually joined is the type of the client declaration.

• Anonymous class syntax, the syntax of the lambda expression omits the interface type and method name,-> the left side is the parameter column, and the right is the method body, when using a block in a lambda expression, if the method must have a return value, you must use return in the chunk. The Interator () method is promoted to the new Java.util.Iterable parent interface.

· The collections sort () method requires that the ordered object must manipulate the Java.lang.Comparable interface, which has a CompareTo () method that must return a number greater than 0, equal to 0, or less than 0 The collections sort () method has another overloaded version that accepts the operands of the Java.util.Comparator interface, and if this version is used, the order is determined by the compare () definition of comparator.

Workaround
1. Operation comparable

import java.util.*;class Account2 implements Comparable<Account2> {    private String name;    private String number;    private int balance;    Account2(String name, String number, int balance) {        this.name = name;        this.number = number;        this.balance = balance;    }    @Override    public String toString() {        return String.format("Account2(%s, %s, %d)", name, number, balance);    }    @Override    public int compareTo(Account2 other) {        return this.balance - other.balance;    }}public class Sort3 {    public static void main(String[] args) {        List accounts = Arrays.asList(                new Account2("Justin", "X1234", 1000),                new Account2("Monica", "X5678", 500),                new Account2("Irene", "X2468", 200)        );        Collections.sort(accounts);        System.out.println(accounts);    }}

2. Operation Comparator

import java.util.*;public class Sort4 {    public static void main(String[] args) {        List words = Arrays.asList("B", "X", "A", "M", "F", "W", "O");        Collections.sort(words);        System.out.println(words);    }}

• In the Java specification, the order-related behavior, usually either the object itself is comparable, or the other specifies that the comparator object tells how to sort, to get the corresponding value according to a key, The Java.util.Map interface can be used in advance to establish the key value corresponding data, and then to obtain the value, as long as the corresponding key can be quickly obtained. The commonly used map operation classes are JAVA.UTIL.HASHMAP and Java.util.TreeMap, which inherit from the abstract class Java.util.AbstractMap.

· Map also supports generic syntax, such as an example of using HashMap:

import java.util.*;import static java.lang.System.out;public class Messages {    public static void main(String[] args)     {        Map<String, String> messages = new HashMap<>();        messages.put("Justin", "Hello!Justin的訊息!");        messages.put("Monica", "給Monica的悄悄話!");        messages.put("Irene", "Irene的可愛貓喵喵叫!");        Scanner console = new Scanner(System.in);       out.print("取得誰的訊息:");        String message = messages.get(console.nextLine());        out.println(message);        out.println(messages);    }}

• If you use TreeMap to establish a key value corresponding, the part of the key is sorted, provided that the object that is the key must manipulate the comparable interface, or the object that specifies the comparator interface when the TreeMap is created.

The properties class inherits the map interface from the hashtable,hashtable operation, and the properties naturally have map behavior. Although you can also use the put () set key value corresponding, get () method to specify the key retrieval value, but the general properties of SetProperty () specifies the string type of key value, GetProperty () specifies the string type of the key, retrieving the value of the string type, Typically called property names and property values.

• If you want to get all the keys in the map, you can call map keyset () to return the set object. Since the keys are not duplicated, it is a matter of course to return with the set operation, and if you want to get all the values in the map, you can use values () to return the collection object.

• If you want to get the key and value of the map at the same time, you can use the EntrySet () method, which returns a set object, each of which is an map.entry instance. You can call Getkey () to get the key and call GetValue () to get the value.

Learning progress Bar /Cumulative) new/cumulative)
lines of code (newBlog volume (Learning time (new/cumulative) Important growth
Goal 4000 rows

24 Articles

350 hours
First week 200/200 2/2 20/20
Second week 200/400 2/4 18/38
Third week 100/500 3/7 22/60
Week Four 300/800 2/9 30/90
Resources
    • Java Learning Notes (8th Edition)
    • Java Learning Note (8th Edition) Learning Guide
    • ...

20145317 Peng Yao Java programming 5th Week of study summary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.