multiple Rational objects

//Driver to exercise the use of multiple Rational objects
public class RationalTester {
public static void main(String[] args){
	RationalNumber r1=new RationalNumber(6,8);
	RationalNumber r2=new RationalNumber(1,3);
	RationalNumber r3,r4,r5,r6,r7;
	System.out.println("First rational number:"+r1);
	System.out.println("Second rational number:"+r2);
	if(r1.isLike(r2))
		System.out.println("r1 and r2 are euqal.");
	else
		System.out.println("r1 and r2 are not equal.");
	r3=r1.reciprocal();
	System.out.println("The reciprocal of r1 is :"+r3);
	r4=r1.add(r2);
	r5=r1.subract(r2);
	r6=r1.multiply(r2);
	r7=r1.divide(r2);
	System.out.println("r1+r2:"+r4);
	System.out.println("r1-r2:"+r5);
	System.out.println("r1*r3:"+r6);
	System.out.println("r1/r2:"+r7);
}
}
//represents one rational number with a numberator and denominator
public class RationalNumber {
private int numerator,denominator;
public RationalNumber(int numer,int denom){
	if(denom==0)
		denom=1;
	if(denom<0){
		numer=numer*-1;
		denom=denom*-1;
	}
	numerator=numer;
	denominator=denom;
	reduce();
}
public int getDenominator(){
	return denominator;
}
public RationalNumber reciprocal(){
	return new RationalNumber(denominator,numerator);
}
public RationalNumber add(RationalNumber op2){
	int commonDenominator=denominator*op2.getDenominator();
	int numerator1=numerator*op2.getDenominator();
	int numerator2=op2.getNumerator()*denominator;
	int sum=numerator1+numerator2;
	return new RationalNumber(sum,commonDenominator);
}
public RationalNumber subract(RationalNumber op2){
	int commonDenominator=denominator*op2.getDenominator();
	int numerator1=numerator*op2.getDenominator();
	int numerator2=op2.getNumerator()*denominator;
	int difference=numerator1-numerator2;
	return new RationalNumber(difference,commonDenominator);
}
public RationalNumber multiply(RationalNumber op2){
	int numer=numerator*op2.getNumerator();
	int denom=denominator*op2.getDenominator();
	return new RationalNumber(numer,denom);
}
public RationalNumber divide(RationalNumber op2){
	return multiply(op2.reciprocal());
}
public boolean isLike(RationalNumber op2){
	return(numerator==op2.getNumerator()&&denominator==op2.getDenominator());
}
public String toString(){
	String result;
	if(numerator==0)
		result="0";
		else
			if(denominator==1)
				result=numerator+" ";
			else
				result =numerator+"/"+denominator;
		return result;
}
private void reduce(){
	if(numerator!=0){
		int common=gcd(Math.abs(numerator),denominator);
		numerator=numerator/common;
		denominator=denominator/common;
	}
}
private int gcd(int num1,int num2){
	while(num1!=num2)
		if(num1>num2)
			num1=num1-num2;
		else
			num2=num2-num1;
	return num1;
}
private int getNumerator() {
	// TODO Auto-generated method stub
	return numerator;
}
}

你可能感兴趣的:(java,四则运算)