创建一个Example类,该类有一个result() 方法,在result()方法内部有两个多项式A=4x-4  、 B=2*x*x-4*x*y+y*y;C=A/B ,最后返回C的值
要求:x和y的值作为该方法的形参,在计算C值以前,先判断A和B的值,当A或B等于零时抛出一个ArithmeticException异常,使用ArithmeticException捕获该异常,在创建ArithmeticException异常时须使用其带形参的构造函数,给形参赋值为“A 或 B =0”,使用getMessage()显示该字符串。
当A、B都不等于零时抛出一个Exception异常,使用Exception捕获该异常,在创建Exception异常时也须使用其带形参的构造函数,给形参赋值为“program is ok!”,使用getMessage()显示该字符串
最后不管A、B是否等于零,都须显示”program is end”(注:使用finally)
为这个类创建一个main()方法,生成两个20以内的整形随机数,调用result()方法,将这两个随机数赋给x和y.,显示最后结果。

解决方案 »

  1.   

    楼主搞得乱七八糟的
    只要B==0然后抛异常,catch里面打印你想输出的值
    A、B不为0时根本没异常你抛什么啊,直接把打印program is ok 的语句放到try语句里自然就执行了
    program is end放到finally打印
      

  2.   

    import java.util.Random;/**
     * @author God
     */
    public class SpecialMath {

    public static float result; public static void main(String[] args) 
    {
    Random r = new Random();
    int num = 20;
    int x,y;
    x = r.nextInt(20);
    System.out.println("x = " + x);
    y = r.nextInt(20);
    System.out.println("y = " + y);
    try
    {
    result(x,y);
    }
    catch(ArithmeticException e)
    {
    System.out.println(e.getMessage());
    return;
    }
    catch(Exception e)
    {
    System.out.println(e.getMessage());
    System.out.println("result = " + result);
    }
    finally
    {
    System.out.println("program is end");
    }
    }

    public static void result(int x, int y) throws Exception
    {
    int a = 4 * x -4;
    int b = 2 * x * x - 4 * x * y + y * y;
    if( a == 0 || b == 0 )
    {
    throw new ArithmeticException("a or b =0");
    }
    if( a != 0 && b != 0)
    {
    result = (float)a/b;;
    throw new Exception("program is ok!");
    }
    }
    }这个程序够变态的:(
      

  3.   

    class ExceptionTest {
        public int test(int x, int y) throws ArithmeticException, Exception {
            if (x == 0 || y == 0)
                throw new ArithmeticException("a or b is zero!");
            if (x != 0 && y != 0)
                throw new Exception("program is ok!");
            int a = 4 * x - 4;
            int b = 2 * x * x - 4 * x * y + y * y;
            return b - a;
        }    public static void main(String[] args) {
            ExceptionTest et = new ExceptionTest();
            int x = (int) (Math.random() * 20);
            System.out.println("x=" + x);
            int y = (int) (Math.random() * 20);
            System.out.println("y=" + y);
            try {
                System.out.println(et.test(x, y));
            } catch (ArithmeticException ae) {
                System.out.println(ae.getMessage());
            } catch (Exception e) {
                System.out.println(e.getMessage());
            } finally {
                System.out.println("program is end!");
            }
        }
    }
      

  4.   

    jeffidea和mingr6370的程序都不错我也差不多能看懂.谢谢
      

  5.   

    jeffidea和mingr6370你们能给我说说下面的问题.
    我看书上写的异常包括:声明异常,抛出异常,捕获异常.
    说说这三者的关系吧.