java实验报告 下载本文

6. 试编写一个除数为0的异常处理过程。 public class Ex7 { public static void main(String []args){ int a=2; int b=0; int c=0; try { c=a/b; } catch (ArithmeticException e) { System.out.println(e.toString()); System.out.println(\除数为0的异常处理\ }finally{ System.out.println(\无论如何都执行\ } } }

7. 除了使用系统定义的异常外,用户还可以自定义异常。其格式为:

public class MyException extends Exception{…}

试自定义一个异常,在计算两个数乘积的方法(Multiply)中,如果结果超过1000则抛出这个异常。方法Multiply定义如下: Static int Multiply(int n,int m) throws MyException{ int re; re =n*m; if(re>1000) throw new MyException(“结果re=”+re+“超过了”+1000); return re; }

完善这个程序,并测试。

public class MyException extends Exception{ public MyException(){ } public MyException(String msg){ super(msg); } static int Multiply(int n,int m) throws MyException{ int re; re =n*m; if(re>1000) throw new MyException(\结果re=\超过了\ return re; } public static void main(String []args){

}

}

try { Multiply(100,20); } catch (MyException e) { System.out.println(\ //e.printStackTrace(); System.out.println(e.toString()); }

2.Java数据流

(1)编写一个计算器,它从键盘中读取操作数和操作符,经过计算后,在屏幕上输出结果。

import java.io.*; class Calculator { public static void main(String[] args) { Calculator cal=new Calculator(); cal.Calculate(); } public double ReadDouble() { double re=0; DataInputStream in =new DataInputStream(System.in); try{ String temp =in.readLine(); re =Double.parseDouble(temp); } catch (IOException e) { System.out.println(\ } return re; } public void Calculate() { byte cmd='q'; do { double op1,op2,re=0; byte op; System.out.print(\请输入操作数1:\ op1 =ReadDouble(); System.out.print(\请输入操作(+、-、*、/):\ op =ReadByte(); System.out.print(\请输入操作数2:\ op2 =ReadDouble();

}

switch(op) { case '+': re =op1 +op2; break; case '-': re =op1 -op2; break; case '*': re =op1 *op2; break; case '/': re =op1 /op2; break; default: System.out.println(\操作符错误\ continue; } System.out.println(\ System.out.print(\退出?(Q/q)\ cmd =ReadByte(); }while(cmd!='Q' && cmd!='q'); }

public byte ReadByte() { byte cmd[] =new byte[10]; try{ System.in.read(cmd); } catch (IOException e) { System.out.println(\ } return cmd[0]; }

在记事本编辑如下源程序: import java.io.*; class Calculator { public static void main(String[] args) { Calculator cal=new Calculator(); cal.Calculate(); } public double ReadDouble() { // 从键盘读取一个Double数

double re=0; DataInputStream in =new DataInputStream(System.in); try{ String temp =in.readLine(); re =Double.parseDouble(temp); } catch (IOException e) { System.out.println(\ } return re; }

public void Calculate() { // 计算 byte cmd='q'; do { double op1,op2,re=0; byte op; System.out.print(\请输入操作数1:\ op1 =ReadDouble(); System.out.print(\请输入操作(+、-、*、/):\ op =ReadByte(); System.out.print(\请输入操作数2:\ op2 =ReadDouble(); switch(op) { case '+': re =op1 +op2; break; case '-': re =op1 -op2; break; case '*': re =op1 *op2; break; case '/': re =op1 /op2; break; default: System.out.println(\操作符错误\ continue; } System.out.println(\ System.out.print(\退出?(Q/q)\