張季躍 201771010139《面向對象程序設計(java)》第九周學習總結java
第一部分:理論知識學習部分程序員
(1)異常:在程序的執行過程當中所發生的異常事件,它 中斷指令的正常執行。編程
(2)Java的異常處理機制能夠控制程序從錯誤產生的 位置轉移到可以進行錯誤處理的位置。數組
(3)程序中出現的常見的錯誤和問題有:用戶輸入錯誤 ,設備錯誤, 物理限制 ,代碼錯誤。網絡
(1)Java把程序運行時可能遇到的錯誤分爲兩類:app
(2)Java中全部的異常類都直接或間接地繼承於 Throwable類。除內置異常類外,程序員可自定義異常類,Java中的異常類可分爲兩大類:less
(1)聲明拋出異常:若是一個方法可能會生成一些異 常,可是該方法並不確切知道如何對這些異常事 件進行處理,此時,這個方法就需聲明拋出這些異常。dom
(2)聲明拋出異常在方法聲明中用throws子句中來指明,l如下4種狀況須要方法用throws子句聲明拋出異常:函數
–方法調用了一個拋出已檢查異常的方法。工具
–程序運行過程當中可能會發生錯誤,而且利用throw語句 拋出一個已檢查異常對象。
–程序出現錯誤。例如,a[-1]= 0;
–Java虛擬機和運行時庫出現的內部異常。
(3)當Java應用程序出現錯誤時,會根據錯誤類型產 生一個異常對象,這個對象包含了異常的類型和 錯誤出現時程序所處的狀態信息。把異常對象遞交給Java編譯器的過程稱爲拋出。
(4)如何拋出異常
–建立這個類的一個對象;
–將該對象拋出。
C.一個方法拋出了異常後,它就不能返回調用者了。
4.斷句:
(1)斷言:是程序的開發和測試階段用於插入一些代碼錯誤檢 測語句的工具。
(2)斷言(assert)語法以下:
一、assert 條件
或者
二、assert 條件:表達式 這兩個形式都會對布爾「條件」進行判斷,若是判斷結果 爲假(false),說明程序已經處於不正確的狀態下,系 統則拋出AssertionError,給出警告而且退出。在第二種 形式中,「表達式」會傳入AssertionError的構造函數中 並轉成一個消息字符串。
第二部分:實驗部分
一、實驗目的與要求
(1) 掌握java異常處理技術;
(2) 瞭解斷言的用法;
(3) 瞭解日誌的用途;
(4) 掌握程序基礎調試技巧;
2、實驗內容和步驟
實驗1:用命令行與IDE兩種環境下編輯調試運行源程序ExceptionDemo一、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(); } } |
修改程序:
ExceptionDemo1:
package 實驗1;
public class ExceptionDemo1 {
public static void main(String args[]) {
int a = 0;
System.out.println(5 / a);
}
}
ExceptionDemo2 :
package 實驗1;
import java.io.*;
public class ExceptionDemo2 {
public static void main(String args[])
{
FileInputStream fis = null;
try {
fis = new FileInputStream("C:\\Users\\張季躍\\Desktop\\text.txt");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//JVM自動生成異常對象
int b;
try {
while((b=fis.read())!=-1)
{
System.out.print(b);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
實驗結果:
實驗2: 導入如下示例程序,測試程序並進行代碼註釋。
測試程序1:
l 在elipse IDE中編輯、編譯、調試運行教材281頁7-1,結合程序運行結果理解程序;
l 在程序中相關代碼處添加新知識的註釋;
l 掌握Throwable類的堆棧跟蹤方法;
程序代碼:
package stackTrace;
import java.util.*;
/**
* A program that displays a trace feature of a recursive method call.
* @version 1.01 2004-05-10
* @author Cay Horstmann
*/
public class StackTraceTest
{
/**
* Computes the factorial of a number
* @param n a non-negative integer
* @return n! = 1 * 2 * . . . * n
*/
public static int factorial(int n)
{
System.out.println("factorial(" + n + "):");
Throwable t = new Throwable();
StackTraceElement[] frames = t.getStackTrace();
for (StackTraceElement f : frames)
System.out.println(f);
int r;
if (n <= 1) r = 1;
else r = n * factorial(n - 1);
System.out.println("return " + r);
return r;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter n: ");
int n = in.nextInt();
factorial(n);
}
}
實驗結果:
測試程序2:
l Java語言的異常處理有積極處理方法和消極處理兩種方式;
l 下列兩個簡答程序範例給出了兩種異常處理的代碼格式。在elipse IDE中編輯、調試運行源程序ExceptionalTest.java,將程序中的text文件更換爲身份證號.txt,要求將文件內容讀入內容,並在控制檯顯示;
l 掌握兩種異常處理技術的特色。
//積極處理方式 import java.io.*;
class ExceptionTest { public static void main (string args[]) { try{ FileInputStream fis=new FileInputStream("text.txt"); } catch(FileNotFoundExcption e) { …… } …… } } |
//消極處理方式
import java.io.*; class ExceptionTest { public static void main (string args[]) throws FileNotFoundExcption { FileInputStream fis=new FileInputStream("text.txt"); } } |
修改程序:
消極處理:
package 實驗2-2;
//消極處理方式
import java.io.*;
class ExceptionTest1 {
public static void main (String args[]) throws IOException
{
File fis=new File("C:\\Users\\張季躍\\Desktop\\身份證號.txt");
FileReader fr = new FileReader(fis);
BufferedReader br = new BufferedReader(fr);
String s, s2 = new String();
while ((s = br.readLine()) != null) {
s2 += s + "\n ";
}
br.close();
System.out.println(s2);
}
}
積極處理:
package 實驗2-2;
//積極處理方式
import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;
class ExceptionTest {
public static void main (String args[])
{
File fis=new File("C:\\Users\\張季躍\\Desktop\\身份證號.txt");
try{
FileReader fr = new FileReader(fis);
BufferedReader br = new BufferedReader(fr);
try {
String s, s2 = new String();
while ((s = br.readLine()) != null) {
s2 += s + "\n ";
}
br.close();
System.out.println(s2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
實驗結果:
實驗3: 編程練習
練習1:
l 編制一個程序,將身份證號.txt 中的信息讀入到內存中;
l 按姓名字典序輸出人員信息;
l 查詢最大年齡的人員信息;
l 查詢最小年齡人員信息;
l 輸入你的年齡,查詢身份證號.txt中年齡與你最近人的姓名、身份證號、年齡、性別和出生地;
l 查詢人員中是否有你的同鄉;
l 在以上程序適當位置加入異常捕獲代碼。
實驗程序:
System.out.println(s2);
}
}
package 實驗3;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Collections;
public class 實驗 {
public static People findPeopleByname(String name) {
People flag = null;
for (People people : peoplelist) {
if(people.getName().equals(name)) {
flag = people;
}
}
return flag;
}
public static People findPeopleByid(String id) {
People flag = null;
for (People people : peoplelist) {
if(people.getnumber().equals(id)) {
flag = people;
}
}
return flag;
}
private static ArrayList<People> agenear(int yourage) {
// TODO Auto-generated method stub
int j=0,min=53,d_value=0,k = 0;
ArrayList<People> plist = new ArrayList<People>();
for (int i = 0; i < peoplelist.size(); i++) {
d_value = peoplelist.get(i).getage() > yourage ?
peoplelist.get(i).getage() - yourage : yourage - peoplelist.get(i).getage() ;
k = d_value < min ? i : k;
min = d_value < min ? d_value : min;
}
for(People people : peoplelist) {
if(people.getage() == peoplelist.get(k).getage()) {
plist.add(people);
}
}
return plist;
}
private static ArrayList<People> peoplelist;
public static void main(String[] args) {
peoplelist = new ArrayList<People>();
Scanner scanner = new Scanner(System.in);
File file = new File("C:\\Users\\張季躍\\Desktop\\身份證號.txt");
try {
FileInputStream files = new FileInputStream(file);
BufferedReader in = new BufferedReader(new InputStreamReader(files));
String temp = null;
while ((temp = in.readLine()) != null) {
String[] information = temp.split("[ ]+");
People people = new People();
people.setName(information[0]);
people.setnumber(information[1]);
int A = Integer.parseInt(information[3]);
people.setage(A);
people.setsex(information[2]);
for(int j = 4; j<information.length;j++) {
people.setplace(information[j]);
}
peoplelist.add(people);
}
} catch (FileNotFoundException e) {
System.out.println("文件未找到");
e.printStackTrace();
} catch (IOException e) {
System.out.println("文件讀取錯誤");
e.printStackTrace();
}
boolean isTrue = true;
while (isTrue) {
System.out.println("******************************************");
System.out.println(" 1.按順序輸出人員信息");
System.out.println(" 2.查詢年齡最大人員的信息");
System.out.println(" 3.查詢年齡最小人員的信息");
System.out.println(" 4.查詢身份證號.txt中年齡與輸入年齡最近的人");
System.out.println(" 5.查詢人員中是否有輸入地址的同鄉");
System.out.println(" 6.退出");
System.out.println("******************************************");
int nextInt = scanner.nextInt();
switch (nextInt) {
case 1:
Collections.sort(peoplelist);
System.out.println(peoplelist.toString());
break;
case 2:
int max=0;
int j,k1 = 0;
for(int i=1;i<peoplelist.size();i++)
{
j = peoplelist.get(i).getage();
if(j>max)
{
max = j;
k1 = i;
}
}
System.out.println("年齡最大:"+peoplelist.get(k1));
break;
case 3:
int min = 100;
int j1,k2 = 0;
for(int i=1;i<peoplelist.size();i++)
{
j1 = peoplelist.get(i).getage();
if(j1<min)
{
min = j1;
k2 = i;
}
}
System.out.println("年齡最小:"+peoplelist.get(k2));
break;
case 4:
System.out.println("年齡:");
int input_age = scanner.nextInt();
ArrayList<People> plist = new ArrayList<People>();
plist = agenear(input_age);
for(People people : plist) {
System.out.println(people.toString());
}
break;
case 5:
System.out.println("請輸入省份");
String find = scanner.next();
for (int i = 0; i <peoplelist.size(); i++)
{
String [] place = peoplelist.get(i).getplace().split("\t");
for(String temp : place) {
if(find.equals(temp)) {
System.out.println(" "+peoplelist.get(i));
break;
}
}
}
break;
case 6:
isTrue = false;
System.out.println("再見!");
break;
default:
System.out.println("輸入有誤");
}
}
}
}
package 實驗3;
public class People implements Comparable<People> {
private String name = null;
private String number = null;
private int age = 0;
private String sex = null;
private String place = null;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getnumber()
{
return number;
}
public void setnumber(String number)
{
this.number = number;
}
public int getage()
{
return age;
}
public void setage(int age )
{
this.age = age;
}
public String getsex()
{
return sex;
}
public void setsex(String sex )
{
this.sex = sex;
}
public String getplace()
{
return place;
}
public void setplace(String place)
{
if(this.place == null) {
this.place = place;
}else {
this.place = this.place+ "\t" +place;
}
}
public int compareTo(People o)
{
return this.name.compareTo(o.getName());
}
public String toString()
{
return name+"\t"+sex+"\t"+age+"\t"+number+"\t"+place+"\n";
}
}
實驗結果:
練習2:
l 編寫一個計算器類,能夠完成加、減、乘、除的操做;
l 利用計算機類,設計一個小學生100之內數的四則運算練習程序,由計算機隨機產生10道加減乘除練習題,學生輸入答案,由程序檢查答案是否正確,每道題正確計10分,錯誤不計分,10道題測試結束後給出測試總分;
l 將程序中測試練習題及學生答題結果輸出到文件,文件名爲test.txt;
l 在以上程序適當位置加入異常捕獲代碼。
實驗程序:
package 實驗3-2;
import java.util.Random;
import java.util.Scanner;
public class 實驗3{
int sum;
public static void main(String[] args) {
實驗3 t=new 實驗3();
System.out.println("考試開始");
t.sum=0;
Random r=new Random();
for(int i=0;i<10;i++) {
t.core();
}
System.out.println("考試結束");
System.out.println("你的總分爲"+t.sum);
}
private void core() {
Random r=new Random();
int m,n;
m=r.nextInt(11);
n=m%4;
switch(n) {
case 0:
int a ,b,c;
a=r.nextInt(101);
b=r.nextInt(101);
System.out.println(a+"+"+"("+b+")"+"=");
Scanner x=new Scanner(System.in);
c=x.nextInt();
if(c!=a+b)
System.out.println("計算失誤");
else {
System.out.println("計算正確");
sum=sum+10;
}
break;
case 1:
int h,g,f;
h=r.nextInt(101);
g=r.nextInt(101);
System.out.println(h+"-"+"("+g+")"+"= ");
Scanner u=new Scanner(System.in);
f=u.nextInt();
if(f!=h-g)
System.out.println("計算失誤");
else {
System.out.println("計算正確");
sum=sum+10;
}
break;
case 2:
int q,w,e;
q=r.nextInt(101);
w=r.nextInt(101);
System.out.println(q+"*"+"("+w+")"+"= ");
Scanner y=new Scanner(System.in);
e=y.nextInt();
if(e!=q*w)
System.out.println("計算失誤");
else {
System.out.println("計算正確");
sum=sum+10;
}
break;
case 3:
double j,k,l;
j=r.nextInt(101);
k=r.nextInt(101);
if(k==0)
k++;
System.out.println(j+"/"+"("+k+")"+"= ");
Scanner z=new Scanner(System.in);
l=z.nextDouble();
if(l!=(j/k)/1.00)
System.out.println("計算失誤");
else {
System.out.println("計算正確");
sum=sum+10;
}
break;
}
}
}
實驗結果:
實驗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 掌握斷言的使用特色及用法。
實驗結果:
實驗程序2:
l 用JDK命令調試運行教材298頁-300頁程序7-2,結合程序運行結果理解程序;
l 並掌握Java日誌系統的用途及用法。
實驗程序:
package logging;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.logging.*;
import javax.swing.*;
/**
* A modification of the image viewer program that logs various events.
* @version 1.03 2015-08-20
* @author Cay Horstmann
*/
public class LoggingImageViewer
{
public static void main(String[] args)
{
if (System.getProperty("java.util.logging.config.class") == null
&& System.getProperty("java.util.logging.config.file") == null)
{
try
{
Logger.getLogger("com.horstmann.corejava").setLevel(Level.ALL);
final int LOG_ROTATION_COUNT = 10;
Handler handler = new FileHandler("%h/LoggingImageViewer.log", 0, LOG_ROTATION_COUNT);
Logger.getLogger("com.horstmann.corejava").addHandler(handler);
}
catch (IOException e)
{
Logger.getLogger("com.horstmann.corejava").log(Level.SEVERE,
"Can't create log file handler", e);
}
}
EventQueue.invokeLater(() ->
{
Handler windowHandler = new WindowHandler();
windowHandler.setLevel(Level.ALL);
Logger.getLogger("com.horstmann.corejava").addHandler(windowHandler);
JFrame frame = new ImageViewerFrame();
frame.setTitle("LoggingImageViewer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Logger.getLogger("com.horstmann.corejava").fine("Showing frame");
frame.setVisible(true);
});
}
}
/**
* The frame that shows the image.
*/
class ImageViewerFrame extends JFrame
{
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 400;
private JLabel label;
private static Logger logger = Logger.getLogger("com.horstmann.corejava");
public ImageViewerFrame()
{
logger.entering("ImageViewerFrame", "<init>");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// set up menu bar
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu menu = new JMenu("File");
menuBar.add(menu);
JMenuItem openItem = new JMenuItem("Open");
menu.add(openItem);
openItem.addActionListener(new FileOpenListener());
JMenuItem exitItem = new JMenuItem("Exit");
menu.add(exitItem);
exitItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
logger.fine("Exiting.");
System.exit(0);
}
});
// use a label to display the images
label = new JLabel();
add(label);
logger.exiting("ImageViewerFrame", "<init>");
}
private class FileOpenListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
logger.entering("ImageViewerFrame.FileOpenListener", "actionPerformed", event);
// set up file chooser
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
// accept all files ending with .gif
chooser.setFileFilter(new javax.swing.filechooser.FileFilter()
{
public boolean accept(File f)
{
return f.getName().toLowerCase().endsWith(".gif") || f.isDirectory();
}
public String getDescription()
{
return "GIF Images";
}
});
// show file chooser dialog
int r = chooser.showOpenDialog(ImageViewerFrame.this);
// if image file accepted, set it as icon of the label
if (r == JFileChooser.APPROVE_OPTION)
{
String name = chooser.getSelectedFile().getPath();
logger.log(Level.FINE, "Reading file {0}", name);
label.setIcon(new ImageIcon(name));
}
else logger.fine("File open dialog canceled.");
logger.exiting("ImageViewerFrame.FileOpenListener", "actionPerformed");
}
}
}
/**
* A handler for displaying log records in a window.
*/
class WindowHandler extends StreamHandler
{
private JFrame frame;
public WindowHandler()
{
frame = new JFrame();
final JTextArea output = new JTextArea();
output.setEditable(false);
frame.setSize(200, 200);
frame.add(new JScrollPane(output));
frame.setFocusableWindowState(false);
frame.setVisible(true);
setOutputStream(new OutputStream()
{
public void write(int b)
{
} // not called
public void write(byte[] b, int off, int len)
{
output.append(new String(b, off, len));
}
});
}
public void publish(LogRecord record)
{
if (!frame.isVisible()) return;
super.publish(record);
flush();
}
}
實驗結果:
實驗程序3:
l 用JDK命令調試運行教材298頁-300頁程序7-2,結合程序運行結果理解程序;
l 按課件66-77內容練習並掌握Elipse的經常使用調試技術。
第三部分:實驗總結:
經過本週的學習,我對於Java程序運行中出現的異常與錯誤有了更深的理解,並初步瞭解瞭如何解決一些簡單的錯誤與異常。可是在實驗過程當中,我發現我儘管能解決掉一些錯誤,但對於這些錯誤所表明的意義仍是不太瞭解,並且對於實驗3-2,我仍是有好多不懂的地方,即便請教了不少同窗也有失誤,左後仍是和同窗一塊兒參考網上的示例程序才完成的。此外,這一週咱們還初步對斷句進行了學習。