1. 程式人生 > >201772020113李清華《面向對象程序設計(java)》第九周學習總結

201772020113李清華《面向對象程序設計(java)》第九周學習總結

order 自動生成 src java pro all n) 導入 異常

1、實驗目的與要求

(1) 掌握java異常處理技術;

(2) 了解斷言的用法;

(3) 了解日誌的用途;

(4) 掌握程序基礎調試技巧;

2、實驗內容和步驟

實驗1:用命令行與IDE兩種環境下編輯調試運行源程序ExceptionDemo1、ExceptionDemo2,結合程序運行結果理解程序,掌握未檢查異常和已檢查異常的區別。

//異常示例1

public class ExceptionDemo1 {

public static void main(String args[]) {

int a = 0;

System.out.println(5 / a);

}

}

//異常示例2

import java.io.*;

public class ExceptionDemo2 {

public static void main(String args[])

{

FileInputStream fis=new FileInputStream("text.txt");//JVM自動生成異常對象

int b;

while((b=fis.read())!=-1)

{

System.out.print(b);

}

fis

.close();

}

}

實驗結果:未檢查異常:

技術分享圖片

技術分享圖片

修改後:

技術分享圖片

技術分享圖片

實驗2 導入以下示例程序,測試程序並進行代碼註釋。

測試程序1:

l 在elipse IDE中編輯、編譯、調試運行教材281頁7-1,結合程序運行結果理解程序;

l 在程序中相關代碼處添加新知識的註釋;

l 掌握Throwable類的堆棧跟蹤方法;

 1 package stackTrace;
 2 
 3 import java.util.*;
 4 
 5 /**
 6  * A program that displays a trace feature of a recursive method call.
7 * @version 1.01 2004-05-10 8 * @author Cay Horstmann 9 */ 10 public class StackTraceTest 11 { 12 /** 13 * Computes the factorial of a number 14 * @param n a non-negative integer 15 * @return n! = 1 * 2 * . . . * n 16 */ 17 public static int factorial(int n) 18 { 19 System.out.println("factorial(" + n + "):"); 20 Throwable t = new Throwable(); 21 StackTraceElement[] frames = t.getStackTrace(); 22 for (StackTraceElement f : frames) 23 System.out.println(f); 24 int r; 25 if (n <= 1) r = 1; 26 else r = n * factorial(n - 1); 27 System.out.println("return " + r); 28 return r; 29 } 30 31 public static void main(String[] args) 32 { 33 Scanner in = new Scanner(System.in); 34 System.out.print("Enter n: "); 35 int n = in.nextInt(); 36 factorial(n); 37 } 38 }

技術分享圖片

測試程序2:

l Java語言的異常處理有積極處理方法和消極處理兩種方式;

l 下列兩個簡答程序範例給出了兩種異常處理的代碼格式。在elipse IDE中編輯、調試運行源程序ExceptionalTest.java,將程序中的text文件更換為身份證號.txt,要求將文件內容讀入內容,並在控制臺顯示;

掌握兩種異常處理技術的特點。

//積極處理方式  

import java.io.*;

class ExceptionTest {

public static void main (string args[])

{

try{

FileInputStream fis=new FileInputStream("text.txt");

}

catchFileNotFoundExcption e

{ …… }

……

}

}

//消極處理方式

import java.io.*;

class ExceptionTest {

public static void main (string args[]) throws FileNotFoundExcption

{

FileInputStream fis=new FileInputStream("text.txt");

}

}

 1 //積極處理方式
 2 package aaa;
 3 import java.io.*;
 4 public class ExceptionTest {
 5     public static void main(String args[]) 
 6     {
 7          FileInputStream fis;
 8         try {
 9             fis = new FileInputStream("text.txt");
10          int b;
11          while((b=fis.read())!=-1)
12          {
13              System.out.print(b);
14          }
15          fis.close();
16         } catch (Exception e) {
17             // TODO 自動生成的 catch 塊
18             e.printStackTrace();
19         }//JVM自動生成異常對象
20      }
21 }
 1 //消極處理方式
 2 package aaa;
 3 import java.io.*;
 4 public class ExceptionTest {
 5     public static void main(String args[]) throws IOException 
 6     {
 7          FileInputStream fis;
 8          fis = new FileInputStream("text.txt");
 9          int b;
10          while((b=fis.read())!=-1)
11          {
12              System.out.print(b);
13          }
14          fis.close();
15      }
16 }

技術分享圖片

技術分享圖片

實驗3: 編程練習

練習1:

l 編制一個程序,將身份證號.txt 中的信息讀入到內存中;

l 按姓名字典序輸出人員信息;

l 查詢最大年齡的人員信息;

l 查詢最小年齡人員信息;

l 輸入你的年齡,查詢身份證號.txt中年齡與你最近人的姓名、身份證號、年齡、性別和出生地;

l 查詢人員中是否有你的同鄉;

l 在以上程序適當位置加入異常捕獲代碼。

  1 package test1;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.File;
  5 import java.io.FileInputStream;
  6 import java.io.FileNotFoundException;
  7 import java.io.IOException;
  8 import java.io.InputStreamReader;
  9 import java.util.ArrayList;
 10 import java.util.Collections;
 11 import java.util.Scanner;
 12 
 13 public class Main{
 14     private static ArrayList<Student> studentlist;
 15     public static void main(String[] args) {
 16         studentlist = new ArrayList<>();
 17         Scanner scanner = new Scanner(System.in);
 18         File file = new File("F:\\身份證號.txt");
 19         try {
 20             FileInputStream fis = new FileInputStream(file);
 21             BufferedReader in = new BufferedReader(new InputStreamReader(fis));
 22             String temp = null;
 23             while ((temp = in.readLine()) != null) {
 24                 
 25                 Scanner linescanner = new Scanner(temp);
 26                 
 27                 linescanner.useDelimiter(" ");    
 28                 String name = linescanner.next();
 29                 String number = linescanner.next();
 30                 String sex = linescanner.next();
 31                 String age = linescanner.next();
 32                 String province =linescanner.nextLine();
 33                 Student student = new Student();
 34                 student.setName(name);
 35                 student.setnumber(number);
 36                 student.setsex(sex);
 37                 int a = Integer.parseInt(age);
 38                 student.setage(a);
 39                 student.setprovince(province);
 40                 studentlist.add(student);
 41 
 42             }
 43         } catch (FileNotFoundException e) {
 44             System.out.println("學生信息文件找不到");
 45             e.printStackTrace();
 46         } catch (IOException e) {
 47             System.out.println("學生信息文件讀取錯誤");
 48             e.printStackTrace();
 49         }
 50         boolean isTrue = true;
 51         while (isTrue) {
 52             System.out.println("選擇你的操作,輸入正確格式的選項");
 53             System.out.println("A.按姓名字典排序");
 54             System.out.println("B.輸出年齡最大和年齡最小的人");
 55             System.out.println("C.尋找老鄉");
 56             System.out.println("D.尋找年齡相近的人");
 57             System.out.println("F.退出");
 58             String m = scanner.next();
 59             switch (m) {
 60             case "A":
 61                 Collections.sort(studentlist);              
 62                 System.out.println(studentlist.toString());
 63                 break;
 64             case "B":
 65                  int max=0,min=100;
 66                  int j,k1 = 0,k2=0;
 67                  for(int i=1;i<studentlist.size();i++)
 68                  {
 69                      j=studentlist.get(i).getage();
 70                  if(j>max)
 71                  {
 72                      max=j; 
 73                      k1=i;
 74                  }
 75                  if(j<min)
 76                  {
 77                    min=j; 
 78                    k2=i;
 79                  }
 80                  
 81                  }  
 82                  System.out.println("年齡最大:"+studentlist.get(k1));
 83                  System.out.println("年齡最小:"+studentlist.get(k2));
 84                 break;
 85             case "C":
 86                  System.out.println("老家?");
 87                  String find = scanner.next();        
 88                  String place=find.substring(0,3);
 89                  for (int i = 0; i <studentlist.size(); i++) 
 90                  {
 91                      if(studentlist.get(i).getprovince().substring(1,4).equals(place)) 
 92                          System.out.println("老鄉"+studentlist.get(i));
 93                  }             
 94                  break;
 95                  
 96             case "D":
 97                 System.out.println("年齡:");
 98                 int yourage = scanner.nextInt();
 99                 int near=agenear(yourage);
100                 int value=yourage-studentlist.get(near).getage();
101                 System.out.println(""+studentlist.get(near));
102                 break;
103             case "F":
104                 isTrue = false;
105                 System.out.println("退出程序!");
106                 break;
107                 default:
108                 System.out.println("輸入有誤");
109 
110             }
111         }
112     }
113         public static int agenear(int age) {      
114         int j=0,min=53,value=0,k=0;
115          for (int i = 0; i < studentlist.size(); i++)
116          {
117              value=studentlist.get(i).getage()-age;
118              if(value<0) value=-value; 
119              if (value<min) 
120              {
121                 min=value;
122                 k=i;
123              } 
124           }    
125          return k;         
126       }
127 
128 }
 1 package test1;
 2 
 3 public class Student implements Comparable<Student> {
 4 
 5     private String name;
 6     private String number ;
 7     private String sex ;
 8     private int age;
 9     private String province;
10    
11     public String getName() {
12         return name;
13     }
14     public void setName(String name) {
15         this.name = name;
16     }
17     public String getnumber() {
18         return number;
19     }
20     public void setnumber(String number) {
21         this.number = number;
22     }
23     public String getsex() {
24         return sex ;
25     }
26     public void setsex(String sex ) {
27         this.sex =sex ;
28     }
29     public int getage() {
30 
31         return age;
32         }
33         public void setage(int age) {
34             // int a = Integer.parseInt(age);
35         this.age= age;
36         }
37 
38     public String getprovince() {
39         return province;
40     }
41     public void setprovince(String province) {
42         this.province=province ;
43     }
44 
45     public int compareTo(Student o) {
46        return this.name.compareTo(o.getName());
47     }
48 
49     public String toString() {
50         return  name+"\t"+sex+"\t"+age+"\t"+number+"\t"+province+"\n";
51     }    
52 }

技術分享圖片

技術分享圖片

技術分享圖片

註:以下實驗課後完成

練習2:

l 編寫一個計算器類,可以完成加、減、乘、除的操作;

l 利用計算機類,設計一個小學生100以內數的四則運算練習程序,由計算機隨機產生10道加減乘除練習題,學生輸入答案,由程序檢查答案是否正確,每道題正確計10分,錯誤不計分,10道題測試結束後給出測試總分;

l 將程序中測試練習題及學生答題結果輸出到文件,文件名為test.txt;

l 在以上程序適當位置加入異常捕獲代碼。

實驗4:斷言、日誌、程序調試技巧驗證實驗。

實驗程序1:

//斷言程序示例

public class AssertDemo {

public static void main(String[] args) {

test1(-5);

test2(-3);

}

private static void test1(int a){

assert a > 0;

System.out.println(a);

}

private static void test2(int a){

assert a > 0 : "something goes wrong here, a cannot be less than 0";

System.out.println(a);

}

}

l 在elipse下調試程序AssertDemo,結合程序運行結果理解程序;

l 註釋語句test1(-5);後重新運行程序,結合程序運行結果理解程序;

l 掌握斷言的使用特點及用法。

 1 package shiyan;
 2 import java.util.Scanner;
 3 import java.io.PrintWriter;
 4 
 5 public class Main {
 6     public static void main(String[] args) throws Exception{
 7         Scanner in=new Scanner(System.in);
 8         PrintWriter output=new PrintWriter("E:/test.txt");
 9         int sum=0;
10         jisuanji js=new jisuanji();
11         for (int i = 0; i < 10; i++) {
12             int a = (int) Math.round(Math.random() * 100);
13             int b = (int) Math.round(Math.random() * 100);
14             int n = (int) Math.round(Math.random() * 3);
15             
16             switch(n)
17                {
18                case 1:
19                    System.out.println(a+"/"+b+"=");
20                    while(b==0){  
21                        b = (int) Math.round(Math.random() * 100); 
22                        }
23                    double c = in.nextDouble();
24                    output.println(a+"/"+b+"="+c);
25                    if (c == js.chu(a,b)) {
26                        sum += 10;
27                        System.out.println("答案正確");
28                    }
29                    else {
30                        System.out.println("答案錯誤");
31                    }
32                 
33                    break;
34                 
35                case 2:
36                    System.out.println(a+"*"+b+"=");
37                    int c1 = in.nextInt();
38                    output.println(a+"*"+b+"="+c1);
39                    if (c1 == js.chen(a, b)) {
40                        sum += 10;
41                        System.out.println("答案正確");
42                    }
43                    else {
44                        System.out.println("答案錯誤");
45                    }
46                    break;
47                case 3:
48                    System.out.println(a+"+"+b+"=");
49                    int c2 = in.nextInt();
50                    output.println(a+"+"+b+"="+c2);
51                    if (c2 == js.jia(a, b)) {
52                        sum += 10;
53                        System.out.println("答案正確");
54                    }
55                    else {
56                        System.out.println("答案錯誤");
57                    }
58                    
59                    break ;
60                case 4:
61                    System.out.println(a+"-"+b+"=");
62                    int c3 = in.nextInt();
63                    output.println(a+"-"+b+"="+c3);
64                    if (c3 == js.jian(a,b)) {
65                        sum += 10;
66                        System.out.println("答案正確");
67                    }
68                    else {
69                        System.out.println("答案錯誤");
70                    }
71                    break ;
72 
73                    } 
74         
75               }
76             System.out.println("成績"+sum);
77             output.println("成績:"+sum);
78             output.close();
79         }
80     }
 1 package shiyan;
 2 
 3 public class jisuanji {
 4     private int a;
 5     private int b;
 6     public int jia(int a,int b)
 7     {
 8         return a+b;
 9     }
10     public int jian(int a,int b)
11     {
12         return a-b;
13     }
14     public int chen(int a,int b)
15     {
16         return a*b;
17     }
18     public int chu(int a,int b)
19     {
20         if(b==0) 
21         {
22             return 0;
23         }
24         else 
25             return a/b;
26     }
27 }

技術分享圖片

技術分享圖片

201772020113李清華《面向對象程序設計(java)》第九周學習總結