2009年4月13日 星期一

lab Fraction equality test

Write a program to implement a method that can check whether 2 fractions are equal. You will implement a class called Fraction consisting of a numerator and a denominator. The equality test of 2 fractions should return a boolean value.

Use the following as the tests.

* 1/2, 2/4
* 5/6, 6/7


Hints:
Fraction f1, f2;
f1.equals(f2);


class程式碼
------------------------------------------------<程式碼開始>--------------------------------------
public class Fraction {
private int numerator, denominator;
public Fraction(int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
boolean equals(Fraction f) {
if(f.denominator * this.numerator - f.numerator * this.denominator == 0)
return true;
else
return false;
}
public String toString()
{
return (numerator + "/" + denominator);
}
}
------------------------------------------------<程式碼結束>--------------------------------------
主程式碼
------------------------------------------------<程式碼開始>--------------------------------------
import java.util.*;
public class Fractionequalitytest {
    public static void main (String args[]) {
        Fraction f1, f2;
        f1 = new Fraction(1, 2);
f2 = new Fraction(2, 4);
System.out.println("f1 = " + f1.toString());
System.out.println("f2 = " + f2.toString());
if(f1.equals(f2))
System.out.println("f1 = f2\n");
else
System.out.println("f1 != f2\n");
f1 = new Fraction(5, 6);
f2 = new Fraction(6, 7);
System.out.println("f1 = " + f1.toString());
System.out.println("f2 = " + f2.toString());
if(f1.equals(f2))
System.out.println("f1 = f2\n");
else
System.out.println("f1 != f2\n");
    }
}
------------------------------------------------<程式碼結束>--------------------------------------
附註:

沒有留言:

張貼留言