Friday, July 9, 2010

Java Lab - Program 1

Difficulty Level - Very Easy

Rational Number Class in Java

Question:

Develop Rational number class in Java. Use JavaDoc comments for documentation.
Your implementation should use efficient representation for a rational number, i.e. (500 / 1000) should be represented as (½).

My Solution

(any further improvements welcomed).

Two classes "rational_main.java" and "rational.java" has been used to implement this.

rational_main.java

import java.util.Scanner;
class rational_main
{
/** Class that contains the main function
* @author Vivek Venkatesh (Your name)
*/

public static void main(String args[])
{
/** Create an instance of "rational" class
* to call the function in it.
*/

rational x = new rational();

//To get input from user

Scanner s = new Scanner(System.in);
int a,b;
System.out.println("\n Enter the Numerator and Denominator:");
a = s.nextInt();
b = s.nextInt();

x.efficient_rep(a,b);
}
}

rational.java

public class rational
{

/** Rational number class
* To give an efficient representation of user's input rational number
* For ex: 500/1000 to be displayed as 1/2
*/

public void efficient_rep(int a, int b)
{

int x=b;
if(a=2;i--)
{
if(a%i==0 && b%i==0)
{
a=a/i;
b=b/i;
}
}
System.out.println(a + "/" + b);
}
}

(This is only one of the solution, and there is a gr8 possibility of even more efficient solution. If u know pls post it.)


Download Source Code


Click the following links,

rational_main.java

rational.java

No comments: