日期:2014-05-20  浏览次数:20773 次

红色部分代码
public class Rational {
int numerator, denominator;
 
Rational(int x, int y) {
numerator = x;
denominator = y;
}
 
Rational add(Rational r) {
int x = denominator * r.denominator;
int y = numerator * r.denominator + r.numerator * denominator;
int gcd = gcd(x, y);
return new Rational(y/gcd, x/gcd);
}
 
Rational subtract(Rational r) {
int x = denominator * r.denominator;
int y = numerator * r.denominator - r.numerator * denominator;
int gcd = gcd(x, y);
return new Rational(y/gcd, x/gcd);
}
 
Rational multiply(Rational r) {
int x = denominator * r.denominator;
int y = numerator * r.numerator;
int gcd = gcd(x, y);
return new Rational(y/gcd, x/gcd);
}
 
Rational divide(Rational r) {
int x = denominator * r.numerator;
int y = numerator * r.denominator;
int gcd = gcd(x, y);
return new Rational(y/gcd, x/gcd);
}
 
public String toString() {
return numerator + "/" + denominator;
}
 
public static int gcd(int x, int y) {
int tmp;
while (x % y != 0) {
tmp = y;
y = x % y;
x = tmp;
}
return y;
}
 
public static void main(String[] args) {
Rational r1 = new Rational(3, 4);
Rational r2 = new Rational(3, 8);
System.out.println("r1 = " + r1);
System.out.println("r2 = " + r2);
System.out.println("r1 + r2 = " + r1.add(r2));
System.out.println("r1 - r2 = " + r1.subtract(r2));
System.out.println("r1 * r2 = " + r1.multiply(r2));
System.out.println("r1 / r2 = " + r1.divide(r2));
}
}
这里的String toString方法有什么用的?系统会自己调用这个方法,然后输出这个格式吗?

------解决方案--------------------
Java code

Rational r2 = new Rational(3, 8);
System.out.println(r2);//这时候打印的是toString方法的返回值,没实现toString的话打印地址

------解决方案--------------------
System.out.println(r2) ;
其实 输出的 是 r2.toString();
 如果没有重写 toString()则输出的是 : 类名@十六进制数 ;可以看看API的Object的toString()