8.1 语法与继承结构
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("必须输入整数");
       }
    }
}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);
    }
}如果父类异常对象在子类异常前被捕捉,则catch子类异常对象的区块将永远不会被执行。
catch括号中列出的异常不得有继承关系,否则会发生编译错误。
在catch区块进行完部分错误处理之后,可以使用throw(注意不是throws)将异常再抛出。如:
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();
    }
}如果抛出的是受检异常,表示你认为客户端有能力且应该处理异常,此时必须在方法上使用throws声明;如果抛出的异常是非受检异常,表示你认为客户端调用方法的时机错了,抛出异常是要求客户端修正这个漏洞再来调用方法,此时也就不用throws声明。
如果使用继承时,父类某个方法声明throws某些异常,子类重新定义该方法时可以:
不声明throws任何异常。
throws父类该方法中声明的某些异常。
throws父类该方法中声明异常的子类。 但是不可以:
throws父类方法中未声明的其他异常。
throws父类方法中声明异常的父类。public class StackTraceDemo1
{
    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();
    }
}要善用堆栈追踪,前提是程序代码中不可有私吞异常的行为。
在使用throw重抛异常时,异常的追踪堆栈起点,仍是异常的发生根源,而不是重抛异常的地方。如:
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();
    }
}程序执行的某个时间点或某个情况下,必然处于或不处于何种状态,这是一种断言。
何时该使用断言?
断言客户端调用方法前,已经准备好某些前置条件(通常在private方法之中)
断言客户端调用方法后,具有方法承诺的结果。
断言对象某个时间点下的状态。
使用断言取代批注。
断言程序流程中绝对不会执行到的程序代码部分。 断言是判定程序中的某个执行点必然是或不是某个状态,所以不能当作像if之类的判断式来使用,assert不应当作程序执行流程的一部分。
若想最后一定要执行关闭资源的动作,try、catch语法可以搭配finally,无论try区块中有无发生异常,若撰写有finally区块,则finally区块一定会被执行。如:
import java.io.*;
import java.util.Scanner;
public class FileUtil
{
    public static String readFile(String name) throws FileNotFoundException
    {
        StringBuilder text = 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();
    }
}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;
    }
}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();
    }
}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("資源被關閉");
    }
}import static java.lang.System.out;
public class AutoClosableDemo2
{    
    public static void main(String[] args) 
    {
        try(ResourceSome some = new ResourceSome();
             ResourceOther other = new ResourceOther())
        {
            some.doSome();
            other.doOther();
        } 
        catch(Exception ex) 
        {
            ex.printStackTrace();
        }
    }
}class ResourceSome implements AutoCloseable 
{
    void doSome() 
    {
        out.println("作一些事");
    }
    @Override
    public void close() throws Exception 
    {
        out.println("資源Some被關閉");
    }
}
class ResourceOther implements AutoCloseable 
{
    void doOther() 
    {
        out.println("作其它事");
    }
    @Override
    public void close() throws Exception 
    {
        out.println("資源Other被關閉");
    }
}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));
    }
}import java.util.*;
public class MapKeyValue2
{
    public static void main(String[] args) 
    {
        Map<String, String> map = new TreeMap<>();
        map.put("one", "一");
        map.put("two", "二");
        map.put("three", "三");
        foreach(map.entrySet());
    }
    static void foreach(Iterable<Map.Entry<String, String>> iterable)
    {
        for(Map.Entry<String, String> entry: iterable)
        {
            System.out.printf("(鍵 %s, 值 %s)%n", 
                    entry.getKey(), entry.getValue());
        }
    }
}问题: 没弄懂Error与Exception的区别
解决过程: 教材中对Exception与RuntimeException有所解释,但是我并没有完全理解二者的区别,于是我通过上网查资料,总结出以下区别:
Exception:在程序中必须使用try、catch进行处理。
RuntimeException:可以不使用try、catch进行处理,但是如果有异常产生,则异常将由JVM进行处理。
问题: 书上p233页的代码范例中的“!input.matches("\d*")”是什么意思?
解决过程: 通过看书上对代码的解析,得到如下解释:String 的 matches() 方法中设定了"\d*",这是规则表示式,表示检查字符串中的字符是不是数字,若是则 matches() 会返回true。
这周的学习变得不像上一周那么困难了,我觉得还是应该立足于基础,一步一步脚踏实地的学习,只有这样才不会熊瞎子劈苞米-啥都不会。我会一直坚持下去,将这个学习精神延续下去。不过这周我的虚拟机出了问题,代码量没有完成目标,截图也没截图,下周会补上。
“Hello”.substring( 0,2 )的值是“He”
填空:System.out.println( “HELLO”.( toLowerCase() ) ) 会输出“hello”
判断:final可以用在类,方法,变量前。(OK) 面向对象中,设计经验可以用(设计模式)表达


我的结对队友是20155221杨泽武 老师您应该是给他单独安排了学习目标,我暂时没有办法进行点评。
| 代码行数(新增/积累) | 博客量(新增/积累 | 学习时间(新增/累积) | |
|---|---|---|---|
| 目标 | 5000行 | 30篇 | 400小时 | 
| 第一周 | 16/16 | 1/1 | 8/8 | 
| 第二周 | 120/120 | 2/2 | 12/12 | 
| 第三周 | 130/150 | 1/1 | 9/9 | 
| 第四周 | 180/200 | 1/1 | 15/15 | 
| 第五周 | 150/300 | 1/1 | 12/12 | 
20155208徐子涵 2016-2017-2 《Java程序设计》第5周学习总结
原文:http://www.cnblogs.com/xuzihan/p/6624263.html