20145238 《Java程序设计》第5周学习总结
教材学习内容总结
第八章异常处理
8.1.1使用try、catch
·教材范例用户连续输入整数,输入0结束后显示输入数的平均值(代码如下)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); }}
·运行结果如下:
·如果用户不小心将30输入为3o则会出现如下结果
原因是Scanner对象nextInt()方法将用户输入的下一字符串直接定义为int型,,不符合对象预期,因此本章同学try以及catch代表错误对象后做一些处理。
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("必須輸入整數"); } }}
·运行结果如下:
若输入30错为3o则运行结果如下:
·若nextInt发生了(InputMismatchException ex)的错误,执行流程就会跳到catch区块,还可继续下一个循环流程:
·运行结果如下:·若编程过程中出现了“unrepored exception IOException must be Caught or declare to be thrown···”
解决:使用try、catch打包System.in.read(),声明throws java.io.IOException。 ·使用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); }}
·如果父类异常对象在子类异常前被捕捉,则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(); }}
·操作对象异常无法使用try、catch处理时,可由方法的客户端一句当时调用的环节信息进行处理,使用throw声明会抛出的异常类型或父类。
·如果使用继承时,父类某个方法声明throws某些异常,子类重新定义该方法时可以:不声明throws任何异常。throws父类该方法中声明的某些异常。throws父类该方法中声明异常的子类。
throws父类方法中未声明的其他异常。throws父类方法中声明异常的父类。在多重方法调用下,异常发生点可能是在某个方法之中,若想得知异常发生的根源,以及多重方法调用下的堆栈传播,可以利用异常对象自动收集的堆栈追踪来取得相关信息,例如调用异常对象的printStackTrace()。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(); }}
·在使用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(); } }
·如果想要让异常堆栈七点为重抛异常的地方,可以使用fillInstackTrance()方法:
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(); } }
·何时使用断点?
断言客户端调用方法前,已经准备好某些前置条件(通常在private方法之中)断言客户端调用方法后,具有方法承诺的结果。
断言对象某个时间点下的状态。
使用断言取代批注。
断言程序流程中绝对不会执行到的程序代码部分。
8.2
FileUtil中通过Scanner搭配FileInputStream来读取文档,实际上Scanner对象有close方法,可以关闭Scanner相关资源与搭配的FileInputSream.断言是判定程序中的某个执行点必然是或不是某个状态,所以不能当作像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(); }}
·若程序撰写先return。而且有finally区块,那么这个区块会先执行,然后再讲返回值返回。
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; }}
·尝试关闭资源语法:想要尝试自动关闭资源的对象,是撰写在try之后的括号中,如果无须catch处理任何异常,可以不用撰写,也不用撰写finally自行尝试关闭资源。
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(); }}
·尝试关闭资源语法可套用的对象,必须操作java.lang.AutoCloseable接口
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被關閉"); }}
第九章Collection与Map
9.1 ·JavaSE中提供了满足各种需求的API,收集对象的行为,都定义在java.collection中,既能收集对象也能驱逐对象。 ·如果手机是具有索引顺序,可以使用数组。 ·List是一种Collection,作用是收集对象,并以索引的方式保留手机的对象顺序import java.util.Arrays;public class ArrayList{ 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特性:数组在内存中会是连续的线性空间,根据索引随机存取时速度快,如果操作上有这类需求时,像是排序,就可使用ArrayList,可得到较好的速度表现。
·LinkedList在操作List接口时,采用了链接(Link)结构。
public class SimpleLinkedList { private class Node { Node(Object o) { this.o = o; } Object o; Node next; } private Node first; public void add(Object elem) { Node node = new Node(elem); if(first == null) { first = node; } else { append(node); } } private void append(Node node) { Node last = first; while(last.next != null) { last = last.next; } last.next = node; } public int size() { int count = 0; Node last = first; while(last != null) { last = last.next; count++; } return count; } public Object get(int index) { checkSize(index); return findElemOf(index); } private void checkSize(int index) throws IndexOutOfBoundsException { int size = size(); if(index >= size) { throw new IndexOutOfBoundsException( String.format("Index: %d, Size: %d", index, size)); } } private Object findElemOf(int index) { int count = 0; Node last = first; while(count < index) { last = last.next; count++; } return last.elem; }}
·在收集过程中若有相同对象,则不再重复收集,如果有这类需求,可以使用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)); }}
·HashSet的操作概念是,在内存中开设空间,每个空间会有个哈希编码。;Queue继承自Collection,所以也具有Collection的add()、remove()、element()等方法,然而Queue定义了自己的offer()、poll()与peek()等方法,最主要的差别之一在于:add()、remove()、element()等方法操作失败时会抛出异常,而offer()、poll()与peek()等方法操作失败时会返回特定值。
;如果对象有操作Queue,并打算以队列方式使用,且队列长度受限,通常建议使用offer()、poll()与peek()等方法。LinkedList不仅操作了List接口,与操作了Queue的行为,所以可以将LinkedList当作队列来使用。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(); } }}
·运行结果如下:
·使用ArrayDeque来操作容量有限的堆栈:
import java.util.*;import static java.lang.System.out;public class Stack { private Deque elems = new ArrayDeque(); private int capacity; public Stack(int capacity) { this.capacity = capacity; } 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()); }}
·运行结果如下:
·队列的前端与尾端进行操作,在前端加入对象与取出对象,在尾端加入对象与取出对象,Queue的子接口Deque就定义了这类行为;java.util.ArrayDeque操作了Deque接口,可以使用ArrayDeque来操作容量有限的堆栈。泛型语法:类名称旁有角括号<>,这表示此类支持泛型。实际加入的对象是客户端声明的类型
import java.util.Arrays;public class ArrayList{ 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; }}
·匿名类语法来说,Lambda表达式的语法省略了接口类型与方法名称,->左边是参数列,而右边是方法本体;在Lambda表达式中使用区块时,如果方法必须有返回值,在区块中就必须使用return。interator()方法提升至新的java.util.Iterable父接口。
·Collections的sort()方法要求被排序的对象必须操作java.lang.Comparable接口,这个接口有个compareTo()方法必须返回大于0、等于0或小于0的数;Collections的sort()方法有另一个重载版本,可接受java.util.Comparator接口的操作对象,如果使用这个版本,排序方式将根据Comparator的compare()定义来决定。
import java.util.*;class StringComparator implements Comparator{ @Override public int compare(String s1, String s2) { return -s1.compareTo(s2); }}public class Sort5{ public static void main(String[] args) { List words = Arrays.asList("B", "X", "A", "M", "F", "W", "O"); Collections.sort(words, new StringComparator()); System.out.println(words); }}
·收集对象并进行排序;
import java.util.*;public class Sort { public static void main(String[] args) { List numbers = Arrays.asList(10, 2, 3, 1, 9, 15, 4); Collections.sort(numbers); System.out.println(numbers); }}
·程序运行截图;
·程序2
import java.util.*;class Account { private String name; private String number; private int balance; Account(String name, String number, int balance) { this.name = name; this.number = number; this.balance = balance; } @Override public String toString() { return String.format("Account(%s, %s, %d)", name, number, balance); } }public class Sort2 { public static void main(String[] args) { List accounts = Arrays.asList( new Account("Justin", "X1234", 1000), new Account("Monica", "X5678", 500), new Account("Irene", "X2468", 200) ); Collections.sort(accounts); System.out.println(accounts); }}
·程序运行结果:
解决方法
1.操作Comparableimport java.util.*;class Account2 implements Comparable{ 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.操作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); }}
·在java的规范中,与顺序有关的行为,通常要不对象本身是Comparable,要不就是另行指定Comparator对象告知如何排序;若要根据某个键来取得对应的值,可以事先利用java.util.Map接口的操作对象来建立键值对应数据,之后若要取得值,只要用对应的键就可以迅速取得。常用的Map操作类为java.util.HashMap与java.util.TreeMap,其继承自抽象类java.util.AbstractMap。
·Map也支持泛型语法,如使用HashMap的范例:
import java.util.*;import static java.lang.System.out;public class Messages { public static void main(String[] args) { Mapmessages = 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); }}
·如果使用TreeMap建立键值对应,则键的部分则会排序,条件是作为键的对象必须操作Comparable接口,或者是在创建TreeMap时指定操作Comparator接口的对象。如:
import java.util.*;public class Messages2 { public static void main(String[] args) { Mapmessages = new TreeMap<>(); messages.put("Justin", "Hello!Justin的訊息!"); messages.put("Monica", "給Monica的悄悄話!"); messages.put("Irene", "Irene的可愛貓喵喵叫!"); System.out.println(messages); } }
Properties类继承自Hashtable,HashTable操作了Map接口,Properties自然也有Map的行为。虽然也可以使用put()设定键值对应、get()方法指定键取回值,不过一般常用Properties的setProperty()指定字符串类型的键值,getProperty()指定字符串类型的键,取回字符串类型的值,通常称为属性名称与属性值。
·如果想取得Map中所有的键,可以调用Map的keySet()返回Set对象。由于键是不重复的,所以用Set操作返回是理所当然的做法,如果想取得Map中所有的值,则可以使用values()返回Collection对象。如:
import java.util.*;import static java.lang.System.out;public class MapKeyValue { public static void main(String[] args) { Mapmap = new HashMap<>(); map.put("one", "一"); map.put("two", "二"); map.put("three", "三"); out.println("顯示鍵"); map.keySet().forEach(key -> out.println(key)); out.println("顯示值"); map.values().forEach(key -> out.println(key)); }}
·如果想同时取得Map的键与值,可以使用entrySet()方法,这会返回一个Set对象,每个元素都是Map.Entry实例。可以调用getKey()取得键,调用getValue()取得值。如:
import java.util.*;public class MapKeyValue2{ public static void main(String[] args) { Mapmap = new TreeMap<>(); map.put("one", "一"); map.put("two", "二"); map.put("three", "三"); foreach(map.entrySet()); } static void foreach(Iterable > iterable) { for(Map.Entry entry: iterable) { System.out.printf("(鍵 %s, 值 %s)%n", entry.getKey(), entry.getValue()); } }}
教材学习中的问题和解决过程
第八章的学习是异常处理,就是我们平时编程过程中会出现的小问题都有了详细的解答。通过本章的学习我知道了使用try、catch语法,JVM会尝试tyr中的代码如果错误便能跳过错误点,比对catch中声明的类型;
并且还了解了很多模块问题出现问题所提示的结果显示,以后的编程中可能会有各种各样的问题,但通过本章的学习了解到了很多问题出现的原因,下次编程若出现,便可以很快地检查对应区域代码,收获颇多。代码调试中的问题和解决过程
代码调试问题和解决在上个片段以及说明。
其他(感悟、思考等,可选)
前几章大量的敲代码工作让同学们的学习都留于形式,只想着完成作业而对代码的理解少之又少。又认真参考了娄老师积极主动敲代码这篇博客,感觉学好java的方法不是“敲”代码,而是“修改”代码,敲好代码以后如果不理解代码的能,可以通过修改代码来具体体会其真正含义。
进步来源于发现问题和解决问题,如果大家不去主动思考,简单机械的完成作业,那学习便失去了意义。代码托管
学习进度条
代码行数(新增/累积) | 博客量(新增/累积) | 学习时间(新增/累积) | 重要成长 | |
---|---|---|---|---|
目标 | 5000行 | 30篇 | 400小时 | |
第一周 | 200/200 | 2/2 | 20/20 | |
第二周 | 300/500 | 2/4 | 18/38 | |
第三周 | 500/1000 | 3/7 | 22/60 | |
第四周 | 300/1300 | 2/9 | 30/90 |
参考资料
- ...