顯示具有 例外處理 標籤的文章。 顯示所有文章
顯示具有 例外處理 標籤的文章。 顯示所有文章

2015年8月16日 星期日

Java 練習(14):判斷是否為正三角形,並拋出自訂例外

Java 7 教學手冊第五版 第十三章習題

12.三角形的三個邊為 a、b、c,請判斷是否為正三角形,並利用try-catch捕捉自訂的例外,這些例外由 triangle()拋出。



public class App13_12
{
 

 public static void main(String[] args)
 {

  try
  {
   Triangle t = new Triangle();
   t.triangle(5, 2, 2);
  } catch (NotTriangle e)
  {
   System.out.println(e.getMessage());
  } catch (EquilateralTriangle e)
  {
   System.out.println(e.getMessage());
  } catch (NotEquilateralTriangle e)
  {
   System.out.println(e.getMessage());
  }

 }
}

class NotTriangle extends Exception
{

 public NotTriangle(int a, int b, int c)
 {
  super("不構成三角形");
 }
}

class EquilateralTriangle extends Exception
{

 public EquilateralTriangle(int a, int b, int c)
 {
  super("這是正三角形");
 }
}

class NotEquilateralTriangle extends Exception
{

 public NotEquilateralTriangle(int a, int b, int c)
 {
  super("這不是正三角形");
 }
}

class Triangle
{

 public void triangle(int a, int b, int c) throws NotTriangle, EquilateralTriangle, NotEquilateralTriangle
 {

  if ((a + b) < c || (a + c) < b || (b + c) < a)
  {
   throw new NotTriangle(a, b, c);
  } else if (a == b && b == c && c == a)
  {
   throw new EquilateralTriangle(a, b, c);
  } else
  {
   throw new NotEquilateralTriangle(a, b, c);
  }
 }
}

2015年7月30日 星期四

Java上課練習:物件的序列化與反序列化

物件的序列化與反序列化


物件必須實作 Serializable 介面 ( 介面中沒有任何抽象方法需要實作 )

將 Student 類別 加入 Serializable 介面

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.io.Serializable;


public class Student implements Serializable{
    private String name;
    private int eng;
    private int math;

    public Student(String name) throws StudentException{
        if(name.length()<2){
            throw new StudentException("名字不能少於兩個字");
        }
        this.name = name;
    }

    public Student(String name, int eng, int math) {
        this(name);//呼叫另一個建構子
        this.eng = eng;
        this.math = math;
    }

    @Override
    public String toString() {
        return "Student{" + "name=" + name + ", eng=" + eng + ", math=" + math + '}';
    }


    }

將 Student 物件 序列化,儲存檔案

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;


public class ObjectOutputStreamTest {

    public static void main(String[] args) {
        Student st=new Student("Tom",100,99);
        try(ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("C:/Users/Administrator/Desktop/MyJava/student.obj"))){
            oos.writeObject(st);
            System.out.println("Student物件儲存成功");
        }catch(IOException e){
            System.out.println(e);
        }

    }

}

將 Student 物件 反序列化,讀取檔案

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class ObjectInputStreamTest {

    public static void main(String[] args) {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:/Users/Administrator/Desktop/MyJava/student.obj"))) {
            Student st = (Student) ois.readObject(); //Object轉型回Student
            System.out.println(st.toString());
        } catch (IOException e) {
            System.out.println(e);
        } catch (ClassNotFoundException e) {
            System.out.println(e);
        }

    }

}

若修改Student類別,新增 avg 欄位,計算平均,執行 ObjectInputStreamTest,會出現版號不一致的問題
注意:每個類別都有自己的版本編號
修改後的類別,編譯器自動產生的版本編號, 與先前序列化物件的版本編號不一致,導致反序列化失敗

如何避免版號不一致的情況? 在程式自行指定版號

修改Student類別,加入版號

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.io.Serializable;


public class Student implements Serializable{
    private static final long serialVersionUID = 1L; //自行指定版號
    private String name;
    private int eng;
    private int math;

    public Student(String name) throws StudentException{
        if(name.length()<2){
            throw new StudentException("名字不能少於兩個字");
        }
        this.name = name;
    }

    public Student(String name, int eng, int math) {
        this(name);//呼叫另一個建構子
        this.eng = eng;
        this.math = math;
    }

    @Override
    public String toString() {
        return "Student{" + "name=" + name + ", eng=" + eng + ", math=" + math + '}';
    }
    }

刪除先前儲存的Student物件
重新執行序列化 ObjectOutputStreamTest,產生新的學生物件 (沒有平均成績)
此時修改學生類別,加入平均的程式碼

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.io.Serializable;


public class Student implements Serializable{ //實作序列化界面
    private static final long serialVersionUID = 1L; //自行指定版號
    private String name;
    private int eng;
    private int math;
    private float avg;
    
    public Student(String name) throws StudentException{
        if(name.length()<2){
            throw new StudentException("名字不能少於兩個字");
        }
        this.name = name;
    }

    public Student(String name, int eng, int math) {
        this(name);//呼叫另一個建構子
        this.eng = eng;
        this.math = math;
        this.avg=(eng+math)/2.0f;
    }

    @Override
    public String toString() {
        return "Student{" + "name=" + name + ", eng=" + eng + ", math=" + math + ", avg=" + avg + '}';
//        return "Student{" + "name=" + name + ", eng=" + eng + ", math=" + math  + '}';
    }
    }
執行反序列化 ObjectInputStreamTest,讀取先前儲存的學生物件
反序列化成功,但由於先前儲存的學生物件沒有平均,反序列化自動將 avg 設為 0

再度執行序列化 ObjectOutputStreamTest,現在儲存的學生有平均
執行反序列化 ObjectInputStreamTest,即可成功讀取平均成績

因平均不需要設定欄位,可以直接計算,所以使用 transient 宣告,並自定反序列化行為,在 Studnet 類別撰寫自定 readObject( ),反序列化物件時,系統會自動執行

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;


public class Student implements Serializable{ //實作序列化界面
    private static final long serialVersionUID = 1L; //自行指定版號
    private String name;
    private int eng;
    private int math;
    transient private float avg;//宣告transient,不需要反序列化
    
    private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException{
        stream.defaultReadObject();//執行反序列化
        this.avg=(eng+math)/2.0f;
    }

    public Student(String name) throws StudentException{
        if(name.length()<2){
            throw new StudentException("名字不能少於兩個字");
        }
        this.name = name;
    }

    public Student(String name, int eng, int math) {
        this(name);//呼叫另一個建構子
        this.eng = eng;
        this.math = math;
//        this.avg=(eng+math)/2.0f;
    }

    @Override
    public String toString() {
        return "Student{" + "name=" + name + ", eng=" + eng + ", math=" + math + ", avg=" + avg + '}';
//        return "Student{" + "name=" + name + ", eng=" + eng + ", math=" + math  + '}';
    }
    }

Java上課練習:讀取或儲存的資料為 String 或 基本資料型別

DataInputStream、DataOutputStream

讀取或儲存的資料為 String 或 基本資料型別 ( byte short char int long float double boolean)

※儲存成檔案

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;


public class DataOutputStreamTest {

    public static void main(String[] args) {
        String filename="C:/Users/Administrator/Desktop/MyJava/student.data";
        String name="TOM";
        int eng=100;
        int math=95;
        float avg=(eng+math)/2.0f;
        
        try(DataOutputStream dos=new DataOutputStream(new FileOutputStream(filename))){
            dos.writeUTF(name); //string
            dos.writeInt(eng); //int
            dos.writeInt(math);
            dos.writeFloat(avg);
            dos.close();
        }catch(IOException e){
            System.out.println(e);
        }

    }

}

※讀取檔案

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;


public class DataInputStreamTest {

    public static void main(String[] args) {
        String filename="C:/Users/Administrator/Desktop/MyJava/student.data";
        
        try(DataInputStream dis=new DataInputStream(new FileInputStream(filename))){
            String name=dis.readUTF();
            int eng=dis.readInt();
            int math=dis.readInt();
            float avg=dis.readFloat();
            dis.close();
            System.out.println(name+" "+eng+" "+math+" "+avg);
        }catch(IOException e){
            System.out.println(e);
        }

    }

}

Java上課練習:從網路上下載圖檔


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

public class DownloadImageFromURLTest {
    
    public static void main(String[] args) {
        String urlString = "http://img2.wikia.nocookie.net/__cb20140410200723/pokemon/images/archive/1/16/20150102074354!025Pikachu_OS_anime_10.png";
        String saveFileName = "C:/Users/Administrator/Desktop/MyJava/Pikach.png";//存檔名稱
        
        try{
        URL url = new URL(urlString);
        //try-with-catch(自動關閉資源)
        try (InputStream is = url.openStream();
             FileOutputStream fos = new FileOutputStream(saveFileName)) {
            byte[] buf=new byte[1024*1024];//1M
            int size;//紀錄實際所讀到的Byte
            while((size=is.read(buf))!=-1){
                fos.write(buf, 0, size);//將緩衝區資料寫入檔案
            }
            System.out.println("存檔成功"+saveFileName);
        }
        }catch(IOException e){
            System.out.println(e);
        }
    }
    
}

Java上課練習:位元組資料流

位元組資料流

例外處理有兩種手段


  1. 捕捉
  2. 方法宣告拋出例外  ( 下面範例是不良示範 )
wrtie ( 陣列 , 從哪個索引開始 , 寫入的資料量 )


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import java.io.*;
public class FileInputStreamTest {

    public static void main(String[] args) throws IOException { //懶得寫 try-catch,拋出例外
        //讀取&寫入非文字檔使用InputStream和OutputStream
        FileInputStream fis=new FileInputStream("C:/Users/Administrator/Desktop/MyJava/AAA.jpg");
        FileOutputStream fos=new FileOutputStream("C:/Users/Administrator/Desktop/MyJava/CopyFile.jpg");
        byte[] buf=new byte[1024];
        int size;//紀錄實際所讀取到的byte數量
        while((size=fis.read(buf))!=-1){
            fos.write(buf,0,size);//將緩衝區寫入檔案
            //wrtie ( 陣列 , 從哪個索引開始 , 寫入的資料量 )
        }
        fis.close();
        fos.close();
    }

}

Java上課練習:字元資料流

字元資料流

FileWriter

巢狀 例外處理,外層 try-catch 捕捉內層 拋出的例外

※讀取AAA.txt檔案,寫入CopyFile.txt


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CopyFileTest {
    
    public static void main(String[] args) {
        FileReader fr = null;
        FileWriter fw = null;
        try {
            try {
                fr = new FileReader("C:/Users/Administrator/Desktop/MyJava/AAA.txt");
                fw = new FileWriter("C:/Users/Administrator/Desktop/MyJava/CopyFile.txt");
                int i;
                while ((i = fr.read()) != -1) {
                    fw.write(i); //將檔案寫入
                }
            } finally { //資源關閉
                if (fr != null) {
                    fr.close();
                }
                if (fw != null) {
                    fw.close();
                }
            }
        } catch (IOException e) { //捕捉所有IOException(含子類別)
            System.out.println(e);
        }
        
    }
    
}

使用緩衝區
BufferedReader、BufferedWriter

所謂的緩衝區,指的是像陣列的概念,預先準備一塊空間來放資料,省去頻繁的硬體操作,提高執行效率


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import java.io.*;

public class CopyFileTest2 {

    public static void main(String[] args) {
        FileReader fr = null;
        FileWriter fw = null;
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            try {
                fr = new FileReader("C:/Users/Administrator/Desktop/MyJava/AAA.txt");
                fw = new FileWriter("C:/Users/Administrator/Desktop/MyJava/CopyFile.txt");
                //將檔案導入緩衝區的資料流  
                br = new BufferedReader(fr);
                bw = new BufferedWriter(fw);
                String s;
                while ((s = br.readLine()) != null) {//讀取一行,當讀取不到資料回回傳null
                    bw.write(s);//輸出字串
                    bw.newLine();//輸出換行
                }
            } finally {
                if (bw != null) {
                    bw.flush();//將緩衝區的資料寫入
                    bw.close();
                }
                if (br != null) {
                    br.close();
                }
            }
        } catch (IOException e) {
            System.out.println(e);
        }

    }

}

用 Java 7 提供的自動關閉資源語法改寫


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.io.*;

public class CopyFileTest3 {

    public static void main(String[] args) {
        //用 Java 7 提供的自動關閉資源語法改寫
        try (BufferedReader br = new BufferedReader(new FileReader("C:/Users/Administrator/Desktop/MyJava/AAA.txt"));
             BufferedWriter bw = new BufferedWriter(new FileWriter("C:/Users/Administrator/Desktop/MyJava/CopyFile.txt"))) {

            String s;
            while ((s = br.readLine()) != null) {//讀取一行,當讀取不到資料回回傳null
                bw.write(s);//輸出字串
                bw.newLine();//輸出換行

            }
            bw.flush();//將緩衝區的資料寫入
        } catch (IOException e) {
            System.out.println(e);
        }

    }

}

2015年7月23日 星期四

Java上課練習:讀取資料檔


  • 撰寫檔案輸入輸出的程式,通常都要明確捕捉例外,因為所產生的例外編譯器會檢查
  • 開啟檔案,可能發生檔案找不到,必須明確處理 FileNotFoundException


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import java.io.FileNotFoundException;
import java.io.FileReader;

public class FileReaderTest {

    public static void main(String[] args) {
        try{
        FileReader fr=new FileReader("C:/MyJava/MyJava/AAA.txt");
        //設定檔案路徑是錯的 例外處理
        }catch(FileNotFoundException e){
            System.out.println(e.getMessage());
        }
    }
}
執行結果:

FileReader 例外處理


  • 查閱 FileReader 類別 建構子 與 read()方法 可能產生的例外
  • 檔案使用完畢,必須關閉檔案,使用 close() 方法來關閉


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileReaderTest {

    public static void main(String[] args) {
        try{
        FileReader fr=new FileReader("C:/MyJava/MyJava/AAA.txt");
        int i;
        while((i=fr.read()) !=-1){ //若檔案讀取進來讀完會回傳-1
            char c=(char)i;//將數字轉為字串
            System.out.println(c);//印出字串
        }
        fr.close();//當檔案讀取完畢後,將資源關閉
        }catch(FileNotFoundException e){
            System.out.println(e.getMessage());
        }catch(IOException e){
            System.out.println(e.getMessage());
        }
    }
}

當發生例外,會導致沒有辦法把資源關閉,所以要額外再做finally判斷


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileReaderTest {

    public static void main(String[] args) {
        FileReader fr=null;
        try {
            fr = new FileReader("C:/Users/Administrator/Desktop/MyJava/AAA.txt");
            int i;
            while ((i = fr.read()) != -1) { //若檔案讀取進來讀完會回傳-1
                char c = (char) i; //將數字轉為字串
                System.out.print(c);//印出字串
            }
           // fr.close();前面發生例外不會執行,所以將關閉的程式碼移到finally
        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }finally{
            try{
                if(fr!=null){
                    fr.close();
                }
            }catch(IOException e){
                System.out.println(e);
            }
        }
    }

}

用 Java 7 新寫法,改善 finally 的 close() 的寫法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileReaderTest2 {

    public static void main(String[] args) {
        //java7新寫法,資源會自動關閉
        try (FileReader fr = new FileReader("C:/Users/Administrator/Desktop/MyJava/AAA.txt")){
            int i;
            while ((i = fr.read()) != -1) { //若檔案讀取進來讀完會回傳-1
                char c = (char) i; //將數字轉為字串
                System.out.print(c);//印出字串
            }
           // fr.close();前面發生例外不會執行,所以將關閉的程式碼移到finally
        } catch (IOException e) {
            //FileNotFoundException是一種IOException
            //所以捕捉IOException等同涵蓋FileNotFoundException
            System.out.println(e.getMessage());
        } catch (Exception e) {
            //剩下只要是一種Exception,通抓
            System.out.println(e.getMessage());
        }
     }
}

Java上課練習:例外處理


  • 設計一個學生例外類別,學生資料出問題時,產生此物件,提供相關的錯誤訊息
  • 設計 StudentException 繼承 RuntimeException


1
2
3
4
5
6
7
8
    //新增StudentException,繼承RuntimeException例外
    public class StudentException extends RuntimeException {
        //建構子
        public StudentException(String message) {
            super(message);//呼叫父類別建構子,設定錯誤訊息
        }

    }

  • 不允許建立學生物件時,名字少於兩個字
  • 發生名字字數太少問題時,建構子產生例外物件,將此例外拋出,讓對方程式知道出了什麼問題
  • 宣告方法可能拋出的例外,使用 throws
  • 方法中拋出例外,使用 throw


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
   //新增Student類別
public class Student {

    private String name;

    //建構子,宣告會拋出StudentException 例外
    public Student(String name) throws StudentException {
        if (name.length() < 2) {
            throw new StudentException("名字不能少於兩個字");
            //下方的程式不會執行
        }
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student{" + "name=" + name + '}';
    }

}
新增StudentTest主類別


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
  import javax.swing.JOptionPane;

public class StudentTest {

    public static void main(String[] args) {
        String name = JOptionPane.showInputDialog("輸入name");
        Student st = new Student(name);
        System.out.println(st); // 自動呼叫 st.toString() 
    }

}
當輸入的名字少於2個字,則會顯示錯誤訊息


所以要加入例外處理


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
 import javax.swing.JOptionPane;

public class StudentTest {

    public static void main(String[] args) {
   boolean repeat;
        do {
            repeat = false;//重設 false
            try {
                String name = JOptionPane.showInputDialog("輸入name");
                Student st = new Student(name);
                System.out.println(st);
            } catch (StudentException se) { //取得例外錯誤訊息
                String msg = se.getMessage();
                JOptionPane.showMessageDialog(null, msg);
                repeat = true; //發生例外,需要重新輸入
            }
        } while (repeat);
    }

}

若不用例外處理,則程式要先判斷


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
 import javax.swing.JOptionPane;

public class StudentTest2 {

    public static void main(String[] args) {
        String name = null;
        do {
            name = JOptionPane.showInputDialog("輸入name");
        } while (name == null || name.length() < 2);
        Student st = new Student(name);
        System.out.println(st);
    }

}