これは、有理数のさまざまな操作を計算する私のコードです。今、私の仕事は、assert
オーバーフローから保護するために追加のセキュリティを実装することです。私は何かをしようとしましたが、JVM でアサーションを有効にすると、(アサート条件が-ea
あっても) 常にアサーションを「スロー」し始めました。これを実装するにはどうすればよいですか?また、数字でそれを行う適切な方法は何ですか?4 > 5
Long
public class Rational {
private final long numerator;
private final long denominator;
private double result;
public Rational(long numerator, long denominator){
this.numerator = numerator;
this.denominator = denominator;
result = (double)numerator/(double)denominator;
}
public Rational plus(Rational b){
assert this.denominator * b.denominator >= Long.MAX_VALUE : "Overflow of denominator in 'PLUS'"; //My attempt
long plusDenominator = this.denominator * b.denominator;
long plusNumerator = ((plusDenominator / this.denominator) * this.numerator) + ((plusDenominator / b.denominator) * b.numerator);
long gcd = gcd(plusNumerator, plusDenominator);
return new Rational(plusNumerator / gcd, plusDenominator / gcd);
}
public Rational minus(Rational b){
long minusDenominator = this.denominator * b.denominator;
long minusNumerator = ((minusDenominator / this.denominator) * this.numerator) - ((minusDenominator / b.denominator) * b.numerator);
long gcd = gcd(minusNumerator, minusDenominator);
return new Rational(minusNumerator / gcd, minusDenominator / gcd);
}
public Rational times(Rational b){
long timesDenominator = this.denominator * b.denominator;
long timesNumerator = this.numerator * b.numerator;
long gcd = gcd(timesDenominator, timesNumerator);
return new Rational(timesNumerator / gcd, timesDenominator / gcd);
}
public Rational divides(Rational b){
long divDenominator = this.denominator * b.numerator;
long divNumerator = this.numerator * b.denominator;
long gcd = gcd(divNumerator, divDenominator);
return new Rational(divNumerator / gcd, divDenominator / gcd);
}
private long gcd(long p, long q){
if(q == 0) return p;
long r = p % q;
return gcd(q, r);
}
public static void main(String[] args){
Rational r1 = new Rational(8, 999999999999999999L);
Rational r2 = new Rational(8 ,999999999999999999L);
System.out.println(r1.plus(r2));
}
}