• 20145110 《Java程序设计》第五周学习总结


    20145110 《Java程序设计》第五周学习总结

    教材学习内容总结

    第8章 异常处理

    8.1 语法与继承架构

    使用try、catch

    • 与C语言中程序流程和错误处理混在一起不同,Java中把正常流程放try块中,错误(异常)处理放catch块中
    • 使用try、catch语法,JVM尝试执行try区块中的程序代码。如果发生错误,执行流程会跳离错误发生点,然后比较catch括号中声明的类型,是否符合被抛出的错误对象类型,如果是,就执行catch区块的程序代码。
       import java.util.*;
    
        public class Average {
        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);
          }
        }
    
    

    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);
            }
        
        }
    

    8.1.2 异常继承架构

    • 设计错误对象都集成自java.lang.Throwable类,Throwable类定义了取得错误信息、堆栈追踪等方法,他有两个子类:java.lang.Errow、java.lang.Exception。
    • 程序设计本身的错误,建议使用Exception或其子类实例来表现,所以通常诚错误处理为异常处理。
    • 如果父类异常对象在子类异常对象前被捕捉,则catch子类异常对象的区块将永远不被执行,编译程序会检查出这个错误。
    import java.util.Scanner;
    public class Average4{
        public static void main(String[] args){
            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);
        }
        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);
        }
    }
    

    8.1.3 要抓还是抛

    • 运行时异常(编译时不检测):在编译时,不需要处理,编译器不检查。该异常的发生,建议不处理,让程序停止,需要对代码进行修正。
    • 编译时被检测异常 :该异常在编译时,如果没有处理(没有抛也没有try),编译失败。该异常被表示,代表可以被处理。
    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();
        }
    }
    

    8.1.5认识堆栈追踪

    定义:若想得知异常发生的根源,以及多重方法调用下异常的堆栈传播,可以利用一场对象自动收集的对堆栈追踪来获取相关信息。

    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.1.6 关于assert

    • assert的两种使用语法:
      1.assert boolean_expression
      2.assert boolean_expression : detail_expression

    8.2 异常与资源管理

    ublic 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;
        }
    }
    

    java.lang.AutoCloseable接口

    public class AutoCloseableDemo {
        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("资源被关闭");
          }
        }
    

    9.1 使用Collection收集对象

    9.1.1 认识Collection

    收集对象的行为,像是新增对象的add()方法、移除对象的remove()方法等,都是定义在java.util.Collection中。既然可以收集对象,也要能逐一取得对象,这就是java.lang.Iterable定义的行为,它定义了iterator()方法返回java.lang.Iterable操作对象,可以让你逐一取得收集的对象。
    List是一种Collection,作用是收集对象,并以索引方式保留收集的对象顺序,其操作类之一是java.util.ArrayList。

     import static java.lang.System.out;
    
        public class Guest
        {
        public static void main(String[] args)
    
        {
            List names = new java.util.ArrayList();
            collectNameTo(names);
            out.println("訪客名單:");
            printUpperCase(names); 
        }
    
    
        static void collectNameTo(List names) 
        {
            Scanner console = new Scanner(System.in);
            while(true)
            {
                out.print("訪客名稱:");
                String name = console.nextLine();
                if(name.equals("quit")) 
                {
                    break;
                }
                names.add(name);
            }
        }
    
        static void printUpperCase(List names)
        {
            for(int i = 0; i < names.size(); i++) 
            {
               String name = (String) names.get(i);
                out.println(name.toUpperCase());
            }        
          }        
        }
    
    • 若收集的对象经常会有变动索引的情况,也许考虑链接方式操作的List会比较好,像是随时会有客户端登录或注销的客户端List,使用LinkedList会有比较好的效率。
    • 在收集过程中若有相同对象,则不再重复收集,如果有这类需求,可以使用Set接口的操作对象。
     import java.util.*;
    
        public class WordCount
    
        {
    
         public static void main(String[] args) 
            {
    
            Scanner console = new Scanner(System.in);
    
            System.out.print("請輸入英文:");
            Set words = tokenSet(console.nextLine());
            System.out.printf("不重複單字有 %d 個:%s%n", words.size(), words);
        }
    
        static Set tokenSet(String line)
        {
            String[] tokens = line.split(" ");
            return new HashSet(Arrays.asList(tokens));
             }
        }
    

    9.2键值对应的Map

    常用的Map操作类为java.util.HashMap与java.util.TreeMap。
    如果想取得Map中所有的键,可以调用Map的keySet()返回Set对象。

    本周代码托管截图

    https://git.oschina.net/20145110/java-besti-is-2015-2016-2-20145110/tree/master/week5?dir=1&filepath=week5&oid=d3477b54e0186e8101b84edf8bdb5a407dff3de0&sha=866dcf114ac3e82f4d1ed2a175b790a614e35bfe

    其他(感悟、思考等,可选)

    java的学习进度还是很快,每周的学习任务较大。所以开始慢慢的会忘记之前所学过的东西,所以我觉得将感悟和体会记录下来是一个很好的总结方式,能够巩固自己所学到的知识。

    学习进度条

    代码行数(新增/累积) 博客量(新增/累积) 学习时间(新增/累积) 重要成长
    目标 5000行 30篇 400小时
    第一周 200/200 1/2 20/20
    第二周 300/500 1/3 18/38
    第三周 500/1000 1/4 22/60
    第四周 300/1300 1/5 45/125
    第五周 300/1600 1/5 30/160

    参考资料

  • 相关阅读:
    js 自定义事件
    django项目mysite
    python web 框架
    Python web-Http
    numpy学习
    django 中单独执行py文件修改用户名
    python解决排列组合
    解决Database returned an invalid datetime value. Are time zone definitions for your database installed?
    Anaconda下载地址
    Django中使用geetest实现滑动验证
  • 原文地址:https://www.cnblogs.com/20145110tyc/p/5351202.html
Copyright © 2020-2023  润新知