package jfractionse; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author gabriele */ public class fraction { private int n; private int d; public fraction() { this.n = this.d = 1; } public fraction(int a) { this.n=a; this.d=1; } fraction(int a, int b)throws IllegalArgumentException { if (b==0) { throw new IllegalArgumentException(); } else { this.n = a; this.d = b; this.reduce(); } } // test di positivita' public boolean is_pos(){ return (this.n > 0); } // operazioni di lettura public int get_numerator() { return this.n; } public int get_denumerator() { return this.d; } // operazioni di scrittura public void set_numerator(int a) { this.n=a; this.reduce(); } public void set_denumerator(int a) throws IllegalArgumentException { if (a==0) { throw new IllegalArgumentException(); } this.d = a; this.reduce(); } // operazioni aritmetiche public fraction sum(fraction f) { fraction tmp= new fraction(); tmp.n = this.n * f.d + this.d * f.n; tmp.d = this.d * f.d; tmp.reduce(); return tmp; } public fraction sub(fraction f) { fraction tmp= new fraction(); tmp.n = this.n * f.d - this.d * f.n; tmp.d = this.d * f.d; tmp.reduce(); return tmp; } public fraction mul(fraction f) { fraction tmp = new fraction(); tmp.n = this.n * f.n; tmp.d = this.d * f.d; tmp.reduce(); return tmp; } public fraction div(fraction f) throws IllegalArgumentException { if (f.n==0) { throw new IllegalArgumentException(); } fraction x = new fraction(f.d,f.n); return this.mul(x); } public String toString() { return " " + this.n +"/"+ this.d +" "; } //--------------------------------------------------- // funzione di utilita' //--------------------------------------------------- private void reduce() { if ( this.n == 0 ) { // frazione uguale a zero this.d=1; return; } if ( this.d < 0 ) { // rendo il denominatore positivo this.n *= -1; this.d *= -1; } int nn=this.n; int dd=this.d; //dd e' sicuramente positivo if (nn <0 ) nn= - nn; //rendo nn positivo while ( nn != dd ) { //applico l'algoritmo di Euclide if ( nn > dd ) nn -= dd; else dd -= nn; } this.n /= nn; this.d /= nn; } }