首页 技术 正文
技术 2022年11月15日
0 收藏 825 点赞 2,952 浏览 10087 个字

20145317彭垚 《Java程序设计》第5周学习总结

教材学习内容总结

  • 第八章

  • 8.1 语法与继承架构
  • 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);
    }
    }

  • Java 中所有错误都会被打包成对象,如果愿意,可以尝试捕捉代表错误的对象后做一些处理
  • 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("必须输入整数");
    }
    }
    }

  • 有时错误可以在捕捉处理之后,尝试恢复程序正常执行流程:
  • 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);
    }
    }

错误会被包装为对象,这些对象都是可抛出的,因此设计错误对象都继承自java.lang.Throwable类,Throwable定义了取得错误信息、堆栈追踪等方法,它有两个子类:java.lang.Error与java.lang.Exception.
Error与其子类实例代表严重系统错误,发生严重系统错误时,Java应用程序本身是无力回复的,Error对象抛出时,基本上不用处理,任其传播至JVM为止,或者是最多留下日志信息。

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

如果父类异常对象在子类异常对象前被捕捉,则catch子类异常对象的区块将永远不会被执行,编译程序会检查出这个错误。
Java的设计上认为,非受检异常是程序设计不当引发的漏洞,异常应自动往外传播,不应使用try、catch来尝试处理,而应改善程序逻辑来避免引发错误。

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是唯一采用受检异常的语言,这有两个目的:一是文件化;二是提供编译程序信息。
查看堆栈追踪最简单的方法,就是直接调用异常对象的printStackTrace().

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

要善用堆栈追踪,前提是程序代码中不可有私吞异常的行为、对异常做了不适当的处理,或显示了不正确的信息。

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 异常与资源管理
无论try区块中有无发生异常,若撰写有finally区块,则finally区块一定会被执行。如果程序撰写的流程中先return了,而且也有finally区块,finally区块会先执行完后,再将值返回。

package CH5;/**
* Created by Administrator on 2016/3/29.
*/
import java.io.*;
import java.util.Scanner;
public class TryCatchFinally {
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();
}
}
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;
}

在JDK之后,新增了尝试关闭资源语法,想要尝试自动关闭资源的对象,是撰写在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();
}
}

JDK的尝试关闭资源语法可套用的对象,必须操作java.lang.AutoCloseable接口,这是JDK7新增的接口。尝试关闭资源语法也可以同时关闭两个以上的对象资源,只要中间以分号分隔。在try的括号中,越后面撰写的对象资源会越早被关闭。

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

第九章

9.1
·JavaSE中提供了满足各种需求的API,收集对象的行为,都定义在java.collection中,既能收集对象也能驱逐对象。
·如果手机是具有索引顺序,可以使用数组。
·List是一种Collection,作用是收集对象,并以索引的方式保留手机的对象顺序

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特性:数组在内存中会是连续的线性空间,根据索引随机存取时速度快,如果操作上有这类需求时,像是排序,就可使用ArrayList,可得到较好的速度表现。
·LinkedList在操作List接口时,采用了链接(Link)结构。
·在收集过程中若有相同对象,则不再重复收集,如果有这类需求,可以使用Set接口的操作对象。
·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来操作容量有限的堆栈。泛型语法:类名称旁有角括号<>,这表示此类支持泛型。实际加入的对象是客户端声明的类型。

·匿名类语法来说,Lambda表达式的语法省略了接口类型与方法名称,->左边是参数列,而右边是方法本体;在Lambda表达式中使用区块时,如果方法必须有返回值,在区块中就必须使用return。interator()方法提升至新的java.util.Iterable父接口。

·Collections的sort()方法要求被排序的对象必须操作java.lang.Comparable接口,这个接口有个compareTo()方法必须返回大于0、等于0或小于0的数;Collections的sort()方法有另一个重载版本,可接受java.util.Comparator接口的操作对象,如果使用这个版本,排序方式将根据Comparator的compare()定义来决定。

解决方法
1.操作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.操作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)
{
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);
}
}

·如果使用TreeMap建立键值对应,则键的部分则会排序,条件是作为键的对象必须操作Comparable接口,或者是在创建TreeMap时指定操作Comparator接口的对象。

Properties类继承自Hashtable,HashTable操作了Map接口,Properties自然也有Map的行为。虽然也可以使用put()设定键值对应、get()方法指定键取回值,不过一般常用Properties的setProperty()指定字符串类型的键值,getProperty()指定字符串类型的键,取回字符串类型的值,通常称为属性名称与属性值。

·如果想取得Map中所有的键,可以调用Map的keySet()返回Set对象。由于键是不重复的,所以用Set操作返回是理所当然的做法,如果想取得Map中所有的值,则可以使用values()返回Collection对象。

·如果想同时取得Map的键与值,可以使用entrySet()方法,这会返回一个Set对象,每个元素都是Map.Entry实例。可以调用getKey()取得键,调用getValue()取得值。

学习进度条

  代码行数(新增/累积) 博客量(新增/累积) 学习时间(新增/累积) 重要成长
目标 4000行

24篇

350小时  
第一周 200/200 2/2 20/20  
第二周 200/400 2/4 18/38  
第三周 100/500 3/7 22/60  
第四周 300/800 2/9 30/90  

参考资料

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,996
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,510
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,353
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,137
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,770
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,848