Java 10th time Job

Source: Internet
Author: User
Tags finally block set time try catch

I. Summary of the study this week 1.1 summarize abnormal content in the way you like (mind map or other).

Two. Written work

This PTA job problem set anomaly

1. Common exceptions

Combined Topic 7-1 Answer

1.1 What exceptions do you often have in code that you have written before, and what do you need to capture (why)? What should be avoided?

A: The most common occurrence must be NullPointerExceptin , it belongs Unchecked Exception to, can not be captured. If you avoid it, you might want to consider the object as null when you write the code, and you need to check the code and modify the code to resolve the exception.

1.2 What kind of exception requires the user to be sure to use capture processing?

A: In addition to the other, all of them Error RuntimeException Checked Exception need to be used try catch to capture

2. Handle exceptions to make your program more robust

Topic 7-2

2.1 Experimental summary. And answer: How can you make your program more robust?
    • Experimental Summary : The key to this problem in int value = Integer.parseInt(line); this statement, if the input line is not an integer, NumberFormatException the exception will occur, it needs to be carried out try catch .
    • answer the question : to make the program more robust, you should handle the exception where it needs to be handled, and if it is written in a program Checked Exception , the program will be more robust after we have processed it.
3. Throw and throws

Topic 7-3
Read Integer.parsetint source code

3.1 Integer.parsetint There is a lot of code thrown out of the exception at the outset, what is the benefit of this practice?

Answer :
Source:

public static int parseint (String s) throws NumberFormatException {return parseint (s,10);} public static int parseint (String s, int radix) throws numberformatexception{/* * Warning:this method May be invoked early during VMS initialization * before Integercache is initialized.     Care must is taken to does use * the ValueOf method.      */if (s = = null) {throw new NumberFormatException ("null");                                        } if (Radix < Character.min_radix) {throw new NumberFormatException ("radix" + Radix +    "Less than Character.min_radix"); } if (Radix > Character.max_radix) {throw new Num    Berformatexception ("radix" + radix + "greater than Character.max_radix");    } int result = 0;    Boolean negative = false;    int i = 0, Len = s.length (); int limit =-INTEGER.MAx_value;    int multmin;    int digit;        if (Len > 0) {char firstchar = s.charat (0); if (Firstchar < ' 0 ') {//Possible leading "+" or "-" if (Firstchar = = '-') {negative = True                ;            Limit = Integer.min_value;            } else if (firstchar! = ' + ') throw numberformatexception.forinputstring (s);            if (len = = 1) throw numberformatexception.forinputstring (s);        i++;        } multmin = Limit/radix; while (I < len) {//accumulating negatively avoids surprises near max_value digit = Character.di            Git (S.charat (i++), radix);            if (Digit < 0) {throw numberformatexception.forinputstring (s); } if (Result < Multmin) {throw Numberformatexception.fori            Nputstring (s); } result *= RaDix            if (Result < limit + digit) {throw numberformatexception.forinputstring (s);        } result-= digit;    }} else {throw numberformatexception.forinputstring (s); } return negative? Result:-result;}

This will make the method more Integer.parsetInt robust by providing more test exceptions.

3.2 What information do you usually need to pass to the caller when you write your own program with 3.1 and analyze your own method of throwing an exception?

A: The information passed to the caller, in addition to the different exceptions have a variety of different corresponding exception, but also according to the actual situation to remind some information.

    • combined with the title of the topic 7-3: if(begin>=end)....IllegalArgumentException("begin:"+begin+" >= end:"+end); , if(begin<0)....IllegalArgumentException("begin:"+begin+" < 0"); Although all is IllegalArgumentException , but according to the actual situation will give the transmission of different information.

    • in conjunction with 3.1 : When NULL is passed in throw new NumberFormatException("null") , the given conversion number exceeds the specified range throw new NumberFormatException("radix " + radix +" greater than Character.MAX_RADIX"); . Although all are NumberFormatException , but according to the actual situation will give the delivery of different information.

4. Improve Arrayintegerstack with exception

Topic 6-3

4.1 In combination with 6-3 code, how does it benefit to use an exception-throwing method to represent a program run-time error? What is the advantage of returning an error value more than a simple one?

A: For a simple return null represents an error or return an error value, using the way to throw an exception, you can make the program user more intuitive and clear sense of the cause of the specific error, as in the 6-3 throws FullStackException and throws EmptyStackException , the stack full and empty case is more intuitive.

4.2 If the inner code of a method throws an exception of type RuntimeException, does the method declaration use the throws keyword, and if the exception that is thrown by the method is declared using the throws keyword, what benefit can it bring us?

A: It throws is possible to throw this exception successfully. The advantage is that the caller knows that it is more intuitive because of runtime exceptions rather than other categories of exceptions.

5. Function questions-capture of multiple exceptions

Topic 6-1

5.1 Combined with 6-1 code, answer: If you can throw multiple exceptions in a try block, and there may be an inheritance relationship between exceptions, what do you need to be aware of when capturing?

A: In a try block if you can throw a variety of exceptions, we can provide a catch block for each exception to handle, the capture must be aware of the scope of the exception in order from small to large, subclass exception before the parent class exception. If a subclass exception is placed after the parent exception, the catch block that causes the child class exception is not executed. In the title 6-1 catch(NumberFormatException e) and catch(IllegalArgumentException e) put in front, catch(Exception e) should be put in the last.

5.2 If you can throw multiple exceptions in a try block, what do you need to be aware of when using Java8 's multiple exception capture syntax?

A: Java8 's multiple exception captures are easier than using multiple catch blocks, requiring only one catch block, for example, in question 6-1, catch(NumberFormatException | IllegalArgumentException | Exception e) but as with the logic of multiple catch blocks, subclasses must precede the parent class.

6. Add exception handling to the following code
byte[] content = null;FileInputStream fis = new FileInputStream("testfis.txt");int bytesAvailabe = fis.available();//获得该文件可用的字节数if(bytesAvailabe>0){    content = new byte[bytesAvailabe];//创建可容纳文件大小的数组    fis.read(content);//将文件内容读入数组}System.out.println(Arrays.toString(content));//打印数组内容
6.1 Correct the code and add the following functions. When the file cannot be found, you need to prompt the user not to find the file xxx, retype the file name, and then try to open it again. If it is another exception, prompt to open or read the file failed!.

Note 1: There are several methods inside that can throw an exception.
Feature 2: You need to add a finally close file. Regardless of whether the above code produces an exception, always be prompted to close the file ing. If closing the file fails, the prompt to close the file failed!
The code is as follows :

byte[] content = null;FileInputStream fis = null;int bytesAvailabe = 0;try {        fis = new FileInputStream("testfis.txt");        bytesAvailabe = fis.available();//获得该文件可用的字节数        if(bytesAvailabe>0){            content = new byte[bytesAvailabe];//创建可容纳文件大小的数组        fis.read(content);        }        System.out.println(Arrays.toString(content));//打印数组内容    } catch (FileNotFoundException e) {    e.printStackTrace();    } catch (IOException e) {    e.printStackTrace();    }finally{        if(fis!=null){            try {                fis.close();            }                 catch (IOException e) {                e.printStackTrace();            }        }        else{                System.out.println("file dosen‘t close!!");      }    }
6.2 Combining the title set 6-2 code, what kind of action to put in the finally block? Why? What do I need to be aware of when closing resources using finally?

Answer :

    • Finally is a certain will execute the content, whether the exception has been caught, and finally there will be a unified place to close the resources, finally block should be put in some resources close operation, like 6-2 is also put resource.close(); in finally inside.
    • When you use finally to close a resource, you should be aware that if you use it earlier System.exit(0) , the finally statement will not execute, so when you close the resource, finally it cannot occur System.exit(0) .
6.3 Using the Java7 in the try-with-resourcesTo rewrite the above code to automatically close the resource. What are the benefits of this approach?

Benefit : try-with-resources The function is to automatically invoke the resource's close () function, which implements the automatic recycling of resources, which is convenient and efficient to write code.

public static void main(String[] args) throws IOException {    byte[] content = null;    try (FileInputStream fis = new FileInputStream("testfis.txt");){        int bytesAvailabe = fis.available();//获得该文件可用的字节数        if(bytesAvailabe>0){            content = new byte[bytesAvailabe];//创建可容纳文件大小的数组            fis.read(content);//将文件内容读入数组        }        System.out.println(Arrays.toString(content));//打印数组内容     } catch (IOException e) {        e.printStackTrace();    
7. Object-oriented design job-Library management system (group completion, no more than 3 students per group)

Log in to lib.jmu.edu.cn to search for books. Then log in to the library information system to view my library. If you want to implement a book borrowing system, try using object-oriented modeling.
Group:
Huang 201621123045
Weng Huahui 201621123042

7.1 Who is the user of this system?

A: Students and administrators.

7.2 Main function modules (not too many) and the owner of each module. Next week everyone is going to submit their own module code and run the video.

Student :
Student Registration
Student Login
View Books
Borrowing books
Return books
Administrator :
View Books
Add a book
Delete a book

7.3 Main class design and class diagram of the system (available)

7.4 How you plan to store library information, address information, reader information, and more.

Store the information of the book using the map key value pair, the key value to put the book, value values put the number of books.
The borrowed information is also stored using the Map key value pair
The reader's information is stored using the Set collection

Three. Code Cloud and PTA

Topic Set: Exceptions

3.1. Code Cloud codes Submission record

In the Code cloud Project, select statistics-commits history-set time period, and then search for and

3.2 PTA Problem set complete situation diagram

Two graphs are required (1. Ranking chart. 2.PTA Submission list diagram)


3.3 Count the amount of code completed this week

The weekly code statistics need to be fused into a single table.

Week Time Number of rows number of new rows Number of files number of new files
1 115 115 17 17
2 421 60S 24 7
3 39] 277 30 6
5 1085 387 38 8
6 1497 412 48 10
7 2033 536 57 9
8 2265 232 60 3
9 2728 32t 65 5
10 3360 632 73 8
11 3958 598 83 10

Java 10th time Job

Related Article

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.