Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Rational Class

807603Oct 23 2007 — edited Oct 23 2007
I'm a student learning Java, and doing this class is proving unexpectedly difficult.
public class Rational {
    
    private int num;
    private int denom;
    
    /** Creates a new instance of Rational */
    public Rational(int num, int denom) {
        this.num = num;
        this.denom = denom;
        int d = gcd(int num, int denom);
    }
    
    private int gcd(int num, int denom){
        while (denom > 0) {
            int q = num/denom;
            int r = num - q*denom;
            num = denom;
            denom = r;
        }
        return(num);
    }
    
    
    
    public Rational add(Rational r){
        return new Rational((this.num*r.denom+this.denom*r.num),this.denom*r.denom);
    }
    
    public Rational sub(Rational r){
        return add(r.neg());
    }
    
    public Rational mult(Rational r){
        return new Rational(this.num*r.num,this.denom*r.denom);
    }
    
    public Rational div(Rational r){
        return mult(r.inv());
    }
    
    public Rational neg(){
        return new Rational(this.num*-1,this.denom);
    }
    
    public Rational inv(){
        return new Rational(this.denom,this.num);
    }
    
    public String toString(){
        return (num +  "/" + denom);
    }
    
}
Main
public static void main(String[] args) {
        Rational r1 = new Rational(1,2);
        Rational r2 = new Rational(3,4);
        Rational r3 = r1.add(r2);
        Rational r4 = r1.sub(r2);
        Rational r5 = r1.mult(r2);
        Rational r6 = r1.div(r2);
        System.out.println(r3);
        System.out.println(r4);
        System.out.println(r5);
        System.out.println(r6);
        }
gcd(int num, int denom) gets a "; expected" error and a ".class expected" error. In addition, I cannot get the GCD to apply to the program and reduce the fraction.
How do I get the GCD to apply itself in the program?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 20 2007
Added on Oct 23 2007
9 comments
314 views