* 12.7在准备类Fraction时,创建一个类nul1denominatoreexception,它必须是一个检查异常,如果类Fraction的对象的分母为0,则抛出其实例。将Fraction类的各种方法完整呈现出来
时间: 2024-03-08 09:46:44 浏览: 52
好的,下面是一个完整的`Fraction`类,包括`NullDenominatorException`异常和其他方法:
```java
public class Fraction {
private int numerator;
private int denominator;
public Fraction(int numerator, int denominator) throws NullDenominatorException {
this.numerator = numerator;
setDenominator(denominator);
}
public void setDenominator(int denominator) throws NullDenominatorException {
if (denominator == 0) {
throw new NullDenominatorException();
}
this.denominator = denominator;
}
public int getNumerator() {
return numerator;
}
public int getDenominator() {
return denominator;
}
public Fraction add(Fraction other) throws NullDenominatorException {
int newDenominator = denominator * other.getDenominator();
int newNumerator = numerator * other.getDenominator() + other.getNumerator() * denominator;
return new Fraction(newNumerator, newDenominator);
}
public Fraction subtract(Fraction other) throws NullDenominatorException {
int newDenominator = denominator * other.getDenominator();
int newNumerator = numerator * other.getDenominator() - other.getNumerator() * denominator;
return new Fraction(newNumerator, newDenominator);
}
public Fraction multiply(Fraction other) throws NullDenominatorException {
int newNumerator = numerator * other.getNumerator();
int newDenominator = denominator * other.getDenominator();
return new Fraction(newNumerator, newDenominator);
}
public Fraction divide(Fraction other) throws NullDenominatorException {
int newNumerator = numerator * other.getDenominator();
int newDenominator = denominator * other.getNumerator();
return new Fraction(newNumerator, newDenominator);
}
public String toString() {
return numerator + "/" + denominator;
}
}
```
在这个类中,除了`NullDenominatorException`异常类之外,还包括了`getNumerator`、`getDenominator`、`add`、`subtract`、`multiply`、`divide`和`toString`方法。这些方法实现了分数的加减乘除和输出等功能。如果分母为0,则在构造函数和`setDenominator`方法中都会抛出`NullDenominatorException`异常。
阅读全文