用java写出上一个代码的测试代码RationalTest
时间: 2024-06-06 18:08:18 浏览: 95
public class RationalTest {
public static void main(String[] args) {
// Testing constructor with numerator and denominator
Rational r1 = new Rational(3, 5);
System.out.println("r1 = " + r1.toString());
// Testing constructor with only numerator
Rational r2 = new Rational(7);
System.out.println("r2 = " + r2.toString());
// Testing constructor with no arguments
Rational r3 = new Rational();
System.out.println("r3 = " + r3.toString());
// Testing add method
Rational r4 = new Rational(1, 2);
Rational r5 = new Rational(3, 4);
Rational r6 = r4.add(r5);
System.out.println(r4.toString() + " + " + r5.toString() + " = " + r6.toString());
// Testing subtract method
Rational r7 = new Rational(5, 6);
Rational r8 = new Rational(2, 3);
Rational r9 = r7.subtract(r8);
System.out.println(r7.toString() + " - " + r8.toString() + " = " + r9.toString());
// Testing multiply method
Rational r10 = new Rational(2, 3);
Rational r11 = new Rational(4, 5);
Rational r12 = r10.multiply(r11);
System.out.println(r10.toString() + " * " + r11.toString() + " = " + r12.toString());
// Testing divide method
Rational r13 = new Rational(3, 4);
Rational r14 = new Rational(2, 5);
Rational r15 = r13.divide(r14);
System.out.println(r13.toString() + " / " + r14.toString() + " = " + r15.toString());
// Testing compareTo method
Rational r16 = new Rational(1, 2);
Rational r17 = new Rational(3, 4);
int result = r16.compareTo(r17);
if (result < 0) {
System.out.println(r16.toString() + " < " + r17.toString());
} else if (result == 0) {
System.out.println(r16.toString() + " = " + r17.toString());
} else {
System.out.println(r16.toString() + " > " + r17.toString());
}
// Testing equals method
Rational r18 = new Rational(6, 8);
Rational r19 = new Rational(3, 4);
if (r18.equals(r19)) {
System.out.println(r18.toString() + " is equal to " + r19.toString());
} else {
System.out.println(r18.toString() + " is not equal to " + r19.toString());
}
}
}
阅读全文