Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

EX: NO. 1 Rational Number Class in Java Date

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 28

EX: NO.

1 Rational number class in Java

DATE:

AIM:

To develop a Rational number class in Java, using JavaDoc comments for


documentation. The implementation should use efficient representation for a rational
number, i.e. (500 / 1000) should be represented as (½).

ALGORITHM:

Step 1: Start the program.


Step 2: Define a class with two integer data fields’ numerator and denominator.
Step 3: Define a constructor to initialize the rational number and to simplify it.
Step 4: Define methods to perform the basic arithmetic operations such as addition,
subtraction, multiplication, division and reciprocal.
Step 5: Call the appropriate functions with the corresponding arguments and display the
result.
Step 6: Stop the program.
PROGRAM:

import java.io.*;
import java.math.*;
public class TestRationalClass
{
private int num;
private int den;

public TestRationalClass(int numerator,int denominator)


{
if(denominator==0)
{
throw new RuntimeException("denominator is zero!");
}
int g=gcd(numerator,denominator);
num=numerator /g;
den=denominator /g;
}

public String toString()


{
if(den==1)
{
return(num+" ");
}
else
{
return(" "+den);
}
}

public TestRationalClass times(TestRationalClass b)


{
return new TestRationalClass(this.num*b.num,this.den*b.den);
}

public TestRationalClass plus(TestRationalClass b)


{
int numerator=(this.num*b.den)+(this.den*b.num);
int denominator=this.den*b.den;
return new TestRationalClass(numerator,denominator);
}

public TestRationalClass subtract(TestRationalClass b)


{
int numerator=(this.num*b.den)-(this.den*b.num);
int denominator=this.den*b.den;
return new TestRationalClass(numerator,denominator);
}

public TestRationalClass reciprocal()


{
return new TestRationalClass(den,num);
}

public TestRationalClass divides(TestRationalClass b)


{
return this.times(b.reciprocal());
}

private static int gcd(int m,int n)


{
if(0==n)
return m;
else
return(gcd(n,m%n));
}

public static void main(String [] args)


{
TestRationalClass r1=new TestRationalClass(16,2);
TestRationalClass r2=new TestRationalClass(12,3);
System.out.println("Rational numbers class");
System.out.println(r1 +" + "+r2+ " = "+r1.plus(r2));
System.out.println(r1 +" - "+r2+ " = "+r1.subtract(r2));
System.out.println(r1 +" * "+r2+ " = "+r1.times(r2));
System.out.println(r1 +" / "+r2+ " = "+r1.divides(r2));
}
}
OUTPUT:

RESULT:

Thus the program to develop a rational number class with methods to perform the
basic arithmetic operations was executed and the output was verified successfully.
EX: NO. 2 Date class in Java

DATE:

AIM:

To develop Date class in Java similar to the one available in java.util package. Use
JavaDoc comments.

ALGORITHM:

Step 1: Start the program.


Step 2: Define an object today to the Date class and store the current date in that object.
Step 3: Change the Date Format to Short, Long and Medium and display the date.
Step 4: Convert the Date to String and print it.
Step 5: Stop the program.
PROGRAM:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class BasicDateFormatting
{
public static void main(String[] args)throws Exception
{
Date today=Calendar.getInstance().getTime();
DateFormat shortFormatter=
SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT);
DateFormat longFormatter=
SimpleDateFormat.getDateInstance(SimpleDateFormat.LONG);
DateFormat mediumFormatter=
SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.MEDIUM,SimpleD
ateFormat.LONG);
System.out.println(shortFormatter.format(today));
System.out.println(longFormatter.format(today));
System.out.println(mediumFormatter.format(today));
String DateAsText=shortFormatter.format(today);
Date TextAsDate=shortFormatter.parse(DateAsText);
System.out.println(TextAsDate);
}
}
OUTPUT:

RESULT:

Thus the program to develop a Date class was executed and the output was
verified successfully.
EX: NO. 3 Lisp-like list in Java

DATE:

AIM:

To implement Lisp-like list in Java. To perform the basic operations such as 'car',
'cdr', and 'cons'.

ALGORITHM:

Step 1: Start the program.


Step 2: Create a class LispCommands with a list in it.
Step 3: Define a function parse to write the elements into the list.
Step 4: Define a function car to return the leading element of the list.
Step 5: Define a function cdr to return the list starting from the second element.
Step 6: Define a function cons which adds an element to the front of the list.
Step 7: Call the respective functions with the appropriate arguments.
Step 8: Stop the program.
PROGRAM:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Logger;

public class LispCommands


{
private String[] tokenList;
private static Logger LOGGER =
Logger.getLogger(LispCommands.class.getName());

public LispCommands()
{
}

private void car()


{
LOGGER.info(tokenList[0]);
}

private void cdr()


{
List<String> list = Arrays.asList(tokenList);
ArrayList<String> slist = new ArrayList<String>(list);
slist.remove(0);
display(slist);
}

private void cons(String args)


{
List<String> arrayList = new
ArrayList<String>(Arrays.asList(tokenList));
arrayList.add(args);
Collections.reverse(arrayList);
display(arrayList);
}

private void parse(String args)


{
ArrayList<String> tokenList = new ArrayList<String>();
if(args != null)
{
StringTokenizer tokens = new StringTokenizer(args,"[]");
while (tokens.hasMoreElements())
{
StringTokenizer commaTokens = new
StringTokenizer(tokens.nextToken(),",");
while (commaTokens.hasMoreElements())
{
String token = commaTokens.nextToken();
if(token != null && !token.trim().equals(""))

tokenList.add(token.trim());
}
}
}
this.tokenList = tokenList.toArray(new String[0]);
}

private void display(Object result)


{
System.out.println();
if(result instanceof String)
LOGGER.info(result.toString());
else if(result.getClass().getName().equals("java.util.ArrayList"))
LOGGER.info(result.toString());
}

public static void main(String[] args)


{
LispCommands L = new LispCommands();
L.parse("[3, 0, 2, 5]");
L.car();
L.cdr();
L.cons("7");
}
}
OUTPUT:

RESULT:

Thus the program to implement Lisp-like list in Java was executed and the output
was verified successfully.
EX: NO. 4 Design a Java interface for ADT Stack

DATE:

AIM:

To design a Java interface for ADT Stack and to develop two different classes
that implements this interface, one using array and the other using linked-list.

ALGORITHM:

Step 1: Start the program.


Step 2: Design an interface for Stack ADT with functions push, pop and display.
Step 3: Define a class to implement the stack using array.
Step 4: Define the functions of the interface accordingly and handle the stack overflow
and underflow exceptions.
Step 5: Define a class to implement the stack using linked list.
Step 6: Define the functions of the interface accordingly and handle the exceptions.
Step 7: Stop the program.
PROGRAM:

import java.io.*;
import java.util.*;
interface Mystack
{
public void pop();
public void push();
public void display();
}
class Stack_array implements Mystack
{
final static int n=5;
int stack[]=new int[n];
int top=-1;
public void push()
{
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
if(top==(n-1))
{
System.out.println(" Stack Overflow");
return;
}
else
{
System.out.println("Enter the element");
int ele=Integer.parseInt(br.readLine());
stack[++top]=ele;
}
}
catch(IOException e)
{
System.out.println("e");
}
}
public void pop()
{
if(top<0)
{
System.out.println("Stack underflow");
return;
}
else
{
int popper=stack[top];
top--;
System.out.println("Popped element:" +popper);
}
}

public void display()


{
if(top<0)
{
System.out.println("Stack is empty");
return;
}
else
{
String str=" ";
for(int i=0;i<=top;i++)
str=str+" "+stack[i]+" <--";
System.out.println("Elements are:"+str);
}
}
}
class Link
{
public int data;
public Link nextLink;
public Link(int d)
{
data= d;
nextLink=null;
}
public void printLink()
{
System.out.print(" --> "+data);
}
}
class Stack_List implements Mystack
{
private Link first;
public Stack_List()
{
first = null;
}
public boolean isEmpty()
{
return first == null;
}
public void push()
{
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the element");
int ele=Integer.parseInt(br.readLine());
Link link = new Link(ele);
link.nextLink = first;
first = link;
}
catch(IOException e)
{
System.err.println(e);
}
}
public Link delete()
{
Link temp = first;
try
{
first = first.nextLink;
}
catch(NullPointerException e)
{
throw e;
}
return temp;
}
public void pop()
{
try
{
Link deletedLink = delete();
System.out.println("Popped: "+deletedLink.data);
}
catch(NullPointerException e)
{
throw e;
}
}
public void display()
{
if(first==null)
System.out.println("Stack is empty");
else
{
Link currentLink = first;
System.out.print("Elements are: ");
while(currentLink != null)
{
currentLink.printLink();
currentLink = currentLink.nextLink;
}
System.out.println("");
}
}
}
class StackADT
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Implementation of Stack using Array");
Stack_array stk=new Stack_array();
int ch=0;
do
{
System.out.println("1.Push 2.Pop 3.Display");
System.out.println("Enter your choice:");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
stk.push();
break;
case 2:
stk.pop();
break;
case 3:
stk.display();
break;
}
}while(ch<4);
System.out.println("Implementation of Stack using Linked List");
Stack_List stk1=new Stack_List();
ch=0;
do
{
System.out.println("1.Push 2.Pop 3.Display");
System.out.println("Enter your choice:");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
stk1.push();
break;
case 2:
try
{
stk1.pop();
}
catch(NullPointerException e)
{
System.out.println("Stack underflown");
}
break;
case 3:
stk1.display();
break;
}
}while(ch<4);
}
}
OUTPUT:

RESULT:

Thus the program to implement Stack ADT using array and linked list was
executed and the output was verified successfully.
EX: NO. 5 Design a Vehicle class hierarchy in Java

DATE:

AIM:

To design a Vehicle class hierarchy in Java and to demonstrate polymorphism.

ALGORITHM:

Step 1: Start the program.


Step 2: Define a class Vehicle with fields register no. and model.
Step 3: Define a method display which displays all the data fields.
Step 4: Define the classes namely Twowheeler, Threewheeler and Fourwheeler as
subclasses of Vehicle class.
Step 5: These subclasses defines a method named display that overrides the super class
method.
Step 6: Create objects for the subclasses and call the appropriate methods.
Step 7: Stop the program.
PROGRAM:

import java.io.*;
class Vehicle
{
String regno;
int model;
Vehicle(String r, int m)
{
regno=r;
model=m;
}
void display()
{
System.out.println("Registration no: "+regno);
System.out.println("Model no: "+model);
}
}

class Twowheeler extends Vehicle


{
int noofwheel;
Twowheeler(String r,int m,int n)
{
super(r,m);
noofwheel=n;
}
void display()
{
System.out.println("Two wheeler tvs");
super.display();
System.out.println("No. of wheel : " +noofwheel);
}
}

class Threewheeler extends Vehicle


{
int noofleaf;
Threewheeler(String r,int m,int n)
{
super(r,m);
noofleaf=n;
}
void display()
{
System.out.println("Three wheeler auto");
super.display();
System.out.println("No. of leaf:" +noofleaf);
}
}

class Fourwheeler extends Vehicle


{
int noofleaf;
Fourwheeler(String r,int m,int n)
{
super(r,m);
noofleaf=n;
}
void display()
{
System.out.println("Four wheeler car");
super.display();
System.out.println("No. of leaf:" +noofleaf);
}
}

public class Vehicledemo


{
public static void main(String arg[])
{
Twowheeler t1;
Threewheeler th1;
Fourwheeler f1;
t1=new Twowheeler("TN74 12345", 1,2);
th1=new Threewheeler("TN74 54321", 4,3);
f1=new Fourwheeler("TN34 45677",5,4);
t1.display();
th1.display();
f1.display();
}
}
OUTPUT:

RESULT:

Thus the program to design vehicle class hierarchy and to demonstrate


polymorphism was executed and the output was verified successfully.
EX: NO. 6 Random Generation of objects

DATE:

AIM:

. To design classes namely Currency, Rupee, and Dollar. To write a program that
randomly generates Rupee and Dollar objects and writes them into a file using object
serialization. To write another program to read that file, and to convert to Rupee if it
reads a Dollar, while leave the value as it is if it reads a Rupee.

ALGORITHM:

Step 1: Start the programs.


Step 2: Define a class Currency as an abstract class with abstract methods.
Step 3: Define the classes Rupee and Dollar as subclasses of Currency.
Step 4: Define the abstract methods of the super class accordingly in each subclass.
Step 5: The dollar value is converted to equivalent rupee value within a method of Dollar
class.
Step 6: Define a class StoreCurrency that randomly generates objects of Rupee and
Dollar classes.
Step 7: These objects are written into a file named currency using object serialization.
Step 8: Define a class ReadCurrency that reads the objects from the file currency, and
displays them.
Step 9: Stop the programs.
PROGRAM:

Currency.java

import java.io.Serializable;
public abstract class Currency implements Serializable
{
protected static final Double DOLLAR_RUPEE_EXCHAGERATE = 44.445D;
public Currency(Double money)
{
super();
this.money = money;
}
protected Double money;
public abstract Double getValue ();
public abstract String getPrintableValue();
}

Rupee.java

public class Rupee extends Currency


{
public Rupee(Double amount)
{
super(amount);
}
public Double getValue()
{
return this.money;
}
public String getPrintableValue()
{
String strValue = "Object Name : Rupee \nINR : Rs " + getValue() +
"\n------------------\n";
return strValue;
}
}

Dollar.java

public class Dollar extends Currency


{
public Dollar(Double money)
{
super(money);
}
public Double getValue()
{
return (this.money * DOLLAR_RUPEE_EXCHAGERATE);
}
public String getPrintableValue()
{
String strValue = "Object Name : Dollar \nUSD : $" + this.money + "
\nINR : Rs" + getValue() + "\n------------------\n";
return strValue;
}
}

StoreCurrency.java

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Random;
public class StoreCurrency
{
public static void main(String[] args) throws
FileNotFoundException,IOException
{
Currency currency = null;
ObjectOutputStream out = new ObjectOutputStream(new
FileOutputStream(new File("currency.dat")));
Random random = new Random();
for (int i = 0; i < 10; i++)
{
int decide = random.nextInt();
Double value = (random.nextDouble() *10);
if ( (decide%2)==0 )
currency = new Rupee(value);
else
currency = new Dollar(value);
out.writeObject(currency);
}
out.writeObject(null);
out.close();
}
}
ReadCurrency.java

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class ReadCurrency
{
public static void main(String[] args) throws IOException,
ClassNotFoundException
{
Currency currency = null;
ObjectInputStream in = new ObjectInputStream(new FileInputStream(new
File("currency.dat")));
while ((currency = (Currency) in.readObject()) != null)
{
System.out.println(currency.getPrintableValue());
}
in.close();
}
}
OUTPUT:

RESULT:

Thus the program to generate objects randomly and to write them into a file using
object serialization was executed. The file was read and the required rupee-dollar
conversions were performed and the output was verified successfully.

You might also like