2009年5月4日 星期一

Lab Java Constructor

Write constructors in the lab Fraction Addition.



class程式碼
------------------------------------------------<程式碼開始>--------------------------------------
public class Fractions {
private int numerator, denominator, red;
public Fractions(int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
public Fractions add(Fractions f) {
int x, a, b;
Fractions ans = new Fractions(1, 1);
ans.numerator = f.denominator * this.numerator + f.numerator * this.denominator;
ans.denominator = f.denominator * this.denominator;
red = reduction (ans.numerator, ans.denominator);
ans.numerator = ans.numerator / red;
ans.denominator = ans.denominator / red;
return ans;
}
public Fractions multiply(Fractions f) {
Fractions ans = new Fractions(1, 1);
ans.numerator = f.numerator * this.numerator;
ans.denominator = f.denominator * this.denominator;
red = reduction (ans.numerator, ans.denominator);
ans.numerator = ans.numerator / red;
ans.denominator = ans.denominator / red;
return ans;
}
private int reduction(int a, int b) {
int x;
if(a<b) {
x = a;
a = b;
b = x;
}
while (b != 0) {
x = a % b;
a = b;
b = x;
}
return a;
}
public String toString()
{
return (numerator + "/" + denominator);
}
}
------------------------------------------------<程式碼結束>--------------------------------------
主程式碼
------------------------------------------------<程式碼開始>--------------------------------------
import java.util.*;
public class JavaConstructor {
    public static void main (String args[]) {
Fractions f1 = new Fractions(4, 2), f2 = new Fractions(1, 3);
        
System.out.println("f1 = " + f1.toString());
System.out.println("f2 = " + f2.toString());
System.out.println("f1 + f2 = " + f1.add(f2).toString());
System.out.println("f1 * f2 = " + f1.multiply(f2).toString() + "\n");
    }
}
------------------------------------------------<程式碼結束>--------------------------------------
附註:

沒有留言:

張貼留言