java高手进,帮忙噢 谢啦

[复制链接]
查看11 | 回复1 | 2010-1-9 22:39:26 | 显示全部楼层 |阅读模式
【当a/b的除数b为零时】这句话中a是什么不清楚。。。如果有定义的话,则应该是try{int result = a/b}catch(ArithmeticException e){throw new ByZeroException();}下面的程序实现了,输入为0时,提示【除数为0,不合法,请重新输入除数!】并在控制台中重新输入值import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;public class TestA { public static void main(String[] args) {BufferedReader stdReader = new BufferedReader(new InputStreamReader(
System.in));String line;try { while ((line = stdReader.readLine()) != null) {
try {
if ("0".equals(line)) {
throw new ByZeroException();
}
} catch (ByZeroException e1) {
System.out.println("除数为0,不合法,请重新输入除数!");
} }} catch (IOException e1) { e1.printStackTrace();}try { stdReader.close();} catch (IOException e) { e.printStackTrace();} } static class ByZeroException extends Exception {}}
回复

使用道具 举报

千问 | 2010-1-9 22:39:26 | 显示全部楼层
ByZeroException.java文件:public class ByZeroException extends Exception {public ByZeroException() { }public ByZeroException(String msg) {
super(msg);}public ByZeroException(String msg, Throwable cause) { super(msg, cause);}public ByZeroException(Throwable cause) {
super(cause);}}ExceptionTest.java文件:import java.util.Scanner;public class ExceptionTest { public static void main(String[] args) {Scanner sca = new Scanner(System.in);boolean flag = false;int a = 0, b = 0;System.out.println("请输入a的值:");a = sca.nextInt();do { System.out.println("请输入b的值:"); b = sca.nextInt(); try {
if(b == 0) {
throw new ByZeroException("除数为0,不合法,请重新输入除数!");
}
System.out.println("a/b =" + a/b);
flag = false; } catch (ByZeroException e) {
flag = true;
System.out.println(e.getMessage()); }} while(flag); }}
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行