Java写出一段测试代码 在准备类Fraction时,创建一个类nul1denominatoreexception,它必须是一个检查异常,如果类Fraction的对象的分母为0,则抛出其实例。将Fraction类的各种方法完整呈现出来
时间: 2024-03-08 15:46:54 浏览: 60
下面是一个例子,展示了如何在 Fraction 类中使用 NullDenominatorException:
```java
public class NullDenominatorException extends Exception {
public NullDenominatorException(String message) {
super(message);
}
}
public class Fraction {
private int numerator;
private int denominator;
public Fraction(int numerator, int denominator) throws NullDenominatorException {
if (denominator == 0) {
throw new NullDenominatorException("分母不能为0");
}
this.numerator = numerator;
this.denominator = denominator;
}
public String toString() {
return numerator + "/" + denominator;
}
public Fraction add(Fraction other) throws NullDenominatorException {
int newNumerator = numerator * other.denominator + other.numerator * denominator;
int newDenominator = denominator * other.denominator;
return new Fraction(newNumerator, newDenominator);
}
public Fraction subtract(Fraction other) throws NullDenominatorException {
int newNumerator = numerator * other.denominator - other.numerator * denominator;
int newDenominator = denominator * other.denominator;
return new Fraction(newNumerator, newDenominator);
}
public Fraction multiply(Fraction other) throws NullDenominatorException {
int newNumerator = numerator * other.numerator;
int newDenominator = denominator * other.denominator;
return new Fraction(newNumerator, newDenominator);
}
public Fraction divide(Fraction other) throws NullDenominatorException {
int newNumerator = numerator * other.denominator;
int newDenominator = denominator * other.numerator;
return new Fraction(newNumerator, newDenominator);
}
public void simplify() {
int gcd = _gcd(numerator, denominator);
numerator /= gcd;
denominator /= gcd;
}
private static int _gcd(int a, int b) {
if (b == 0) {
return a;
}
return _gcd(b, a % b);
}
}
```
下面是一段测试代码:
```java
try {
// 创建一个分母为0的分数
Fraction f = new Fraction(1, 0);
System.out.println("分数为:" + f);
} catch (NullDenominatorException e) {
System.out.println("发生异常:" + e.getMessage());
}
// 创建两个分数
Fraction f1 = new Fraction(1, 2);
Fraction f2 = new Fraction(3, 4);
// 进行加法运算
Fraction f3 = f1.add(f2);
System.out.println(f1 + " + " + f2 + " = " + f3);
// 进行减法运算
Fraction f4 = f1.subtract(f2);
System.out.println(f1 + " - " + f2 + " = " + f4);
// 进行乘法运算
Fraction f5 = f1.multiply(f2);
System.out.println(f1 + " * " + f2 + " = " + f5);
// 进行除法运算
Fraction f6 = f1.divide(f2);
System.out.println(f1 + " / " + f2 + " = " + f6);
// 简化分数
Fraction f7 = new Fraction(2, 4);
System.out.println("原分数:" + f7);
f7.simplify();
System.out.println("简化后的分数:" + f7);
```
当分母为0时,运行上述代码会抛出 NullDenominatorException 异常。如果分母不为0,会进行加、减、乘、除、简化等运算,并输出结果。
阅读全文