Showing posts with label Java Lab. Show all posts
Showing posts with label Java Lab. Show all posts

Thursday, September 16, 2010

OPAC System program in Java

Question

Develop a simple OPAC system for library using even-driven and concurrent programming paradigms of Java. Use JDBC to connect to a back-end database.

Procedure

  1. Create a new Database file in MS ACCESS (our backend) named “books.mdb”.

  2. Then create a table named “Library” in it.

  3. The table Library contains the following fields and data types,

  1. AuthorName – Text

  2. ISBN – Text

  3. BookName - Text

  4. Price - Number

  5. Publisher – Text

  1. Enter various records as you wish.

  2. Save the database file.

  3. Next step is to add our “books.mdb” to the System DSN. To do that follow the procedure given below,

  1. Go to Start-> Control Panel -> Administrative tools.

  2. In that double click “Data Sources (ODBC)”.

  3. ODBC Data Source Administrator dialog appears.

  4. In that select “System DSN” tab and click the Add Button.

  5. Select “Microsoft Access Driver(*.mdb)” and click Finish.

  6. ODBC Microsoft Access Setup appears. In the “Data Source name” type “Library”.

  7. Click on the “Select” button and choose your database file. Then click ok.

Now your database file gets added to the System DSN. It should look like below,


Now execute the following code “Library.java”.


Library.java

import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;

public class Library implements ActionListener
{
JRadioButton rbauthor = new JRadioButton("Search by Author name");
JRadioButton rbbook = new JRadioButton("Search by Book name");
JTextField textfld = new JTextField(30);
JLabel label = new JLabel("Enter Search Key");
JButton searchbutton = new JButton("Search");
JFrame frame = new JFrame();
JTable table;
DefaultTableModel model;
String query = "select * from Library";

public Library()
{
frame.setTitle("Online Public Access Catalog");
frame.setSize(500,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());

JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();

p1.setLayout(new FlowLayout());
p1.add(label);
p1.add(textfld);

ButtonGroup bg = new ButtonGroup();
bg.add(rbauthor);
bg.add(rbbook);

p2.setLayout(new FlowLayout());
p2.add(rbauthor);
p2.add(rbbook);
p2.add(searchbutton);
searchbutton.addActionListener(this);

p3.setLayout(new BorderLayout());
p3.add(p1,BorderLayout.NORTH);
p3.add(p2,BorderLayout.CENTER);

frame.add(p3,BorderLayout.NORTH);
addTable(query);
frame.setVisible(true);
}
public void addTable(String s)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:Library","","");
Statement st = conn.createStatement();

ResultSet rs = st.executeQuery(s);
ResultSetMetaData md = rs.getMetaData();
int cols = md.getColumnCount();
model = new DefaultTableModel(1,cols);
table = new JTable(model);
String[] tabledata = new String[cols];
int i=0;
while(i0)
model.removeRow(0);
frame.remove(table);
addTable(query);
}
public static void main(String[] args)
{
new Library();
}

}

Screenshots of Output

(Opening Screen)


(author Search)

(Book Search)



Download the Source Code


Library.java



Saturday, September 11, 2010

Multithreading using Pipes Program

Question

Write a multi-threaded Java program to print all numbers below 100,000 that are
both prime and fibonacci number (some examples are 2, 3, 5, 13, etc.). Design a
thread that generates prime numbers below 100,000 and writes them into a pipe.
Design another thread that generates fibonacci numbers and writes them to another pipe. The main thread should read both the pipes to identify numbers common to both.

Program Written by
Mr.G.Kumaresan sir.

Program


import java.util.*;
import java.io.*;

class Fibonacci extends Thread
{
private PipedWriter out = new PipedWriter();
public PipedWriter getPipedWriter()
{
return out;
}
public void run()
{
Thread t = Thread.currentThread();
t.setName("Fibonacci");
System.out.println(t.getName() + " thread started");
int fibo1=0,fibo2=1,fibo=0;
while(true)
{
try
{
fibo = fibo1 + fibo2;
if(fibo>100000)
{
out.close();
break;
}
out.write(fibo);
sleep(1000);
}
catch(Exception e)
{
System.out.println("Fibonacci:"+e);
}
fibo1=fibo2;
fibo2=fibo;
}
System.out.println(t.getName() + " thread exiting");

}
}
class Prime extends Thread
{
private PipedWriter out1 = new PipedWriter();
public PipedWriter getPipedWriter()
{
return out1;
}
public void run()
{
Thread t= Thread.currentThread();
t.setName("Prime");
System.out.println(t.getName() + " thread Started...");
int prime=1;
while(true)
{
try
{
if(prime>100000)
{
out1.close();
break;
}
if(isPrime(prime))
out1.write(prime);
prime++;
sleep(0);
}
catch(Exception e)
{
System.out.println(t.getName() + " thread exiting.");
System.exit(0);
}
}
}
public boolean isPrime(int n)
{
int m=(int)Math.round(Math.sqrt(n));
if(n==1 || n==2)
return true;
for(int i=2;i<=m;i++)
if(n%i==0)
return false;
return true;
}
}
public class PipedIo
{
public static void main(String[] args) throws Exception
{
Thread t=Thread.currentThread();
t.setName("Main");
System.out.println(t.getName() + " thread Started...");
Fibonacci fibonacci = new Fibonacci();
Prime prime = new Prime();
PipedReader fpr = new PipedReader(fibonacci.getPipedWriter());
PipedReader ppr = new PipedReader(prime.getPipedWriter());
fibonacci.start();
prime.start();
int fib=fpr.read(), prm=ppr.read();
System.out.println("The numbers common to PRIME and FIBONACCI:");
while((fib!=-1) && (prm!=-1))
{
while(prm<=fib)
{
if(fib==prm)
System.out.println(prm);
prm=ppr.read();
}
fib=fpr.read();
}
System.out.println(t.getName() + " thread exiting");
}
}

Download Source Code

PipedIo.java

Friday, August 27, 2010

A Simple Scientific Calculator in Java

Hi Friends....just had some free time, so thought of creating a "Simple Calculator" in Java...As claims it is "Simple" and don't expect anything Big out of it (Just some basic operations).....I have added the source code for it too....

(You can use it to Create your own Calculator and may be which is more efficient than mine..Just in case u find any flaws in this, pls do mail me abt it..)

Screenshot of "Calculator" that I created in Java




Download the Source Code and the Application


Comments Welcomed...

G.Vivek Venkatesh

Tuesday, August 24, 2010

Object Serialization Program in Java

Question

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

Program

(credits to Kumresan Sir)


SerializationWrite.java

import java.io.*;
import java.util.*;

class Currency implements Serializable
{
protected String currency;
protected int amount;

public Currency(String cur, int amt)
{
this.currency = cur;
this.amount = amt;
}
public String toString()
{
return currency + amount;
}
public String dollarToRupee(int amt)
{
return "Rs" + amt * 45;
}
}
class Rupee extends Currency
{
public Rupee(int amt)
{
super("Rs",amt);
}
}
class Dollar extends Currency
{
public Dollar(int amt)
{
super("$",amt);
}
}
public class SerializationWrite
{
public static void main(String args[])
{
Random r = new Random();
try
{
Currency currency;
FileOutputStream fos = new FileOutputStream("serial.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
System.out.println("Writing to file using Object Serialization:");
for(int i=1;i<=25;i++)
{
Object[] obj = { new Rupee(r.nextInt(5000)),new Dollar(r.nextInt(5000)) };
currency = (Currency)obj[r.nextInt(2)]; // RANDOM Objects for Rs and $
System.out.println(currency);
oos.writeObject(currency);
oos.flush();
}
oos.close();
}
catch(Exception e)
{
System.out.println("Exception during Serialization: " + e);
}
}
}

SerializationRead.java

import java.io.*;
import java.util.*;

public class SerializationRead
{
public static void main(String args[])
{
try
{
Currency obj;
FileInputStream fis = new FileInputStream("serial.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
System.out.println("Reading from file using Object Serialization:");
for(int i=1;i<=25;i++)
{
obj = (Currency)ois.readObject();
if((obj.currency).equals("$"))
System.out.println(obj + " = " + obj.dollarToRupee(obj.amount));
else
System.out.println(obj + " = " + obj);

}
ois.close();
}
catch(Exception e)
{
System.out.println("Exception during deserialization." + e);
}
}
}


Output

vivek@ubuntu:~/Desktop$ javac SerializationWrite.java
vivek@ubuntu:~/Desktop$ java SerializationWrite

Writing to file using Object Serialization:
$4645
Rs105
$2497
$892
Rs1053
Rs1270
$1991
Rs4923
Rs4443
Rs3537
Rs2914
$53
$561
$4692
Rs860
$2764
Rs752
$1629
$2880
Rs2358
Rs3561
$3796
Rs341
Rs2010
Rs427

vivek@ubuntu:~/Desktop$ javac SerializationRead.java
vivek@ubuntu:~/Desktop$ java SerializationRead

Reading from file using Object Serialization:
$4645 = Rs209025
Rs105 = Rs105
$2497 = Rs112365
$892 = Rs40140
Rs1053 = Rs1053
Rs1270 = Rs1270
$1991 = Rs89595
Rs4923 = Rs4923
Rs4443 = Rs4443
Rs3537 = Rs3537
Rs2914 = Rs2914
$53 = Rs2385
$561 = Rs25245
$4692 = Rs211140
Rs860 = Rs860
$2764 = Rs124380
Rs752 = Rs752
$1629 = Rs73305
$2880 = Rs129600
Rs2358 = Rs2358
Rs3561 = Rs3561
$3796 = Rs170820
Rs341 = Rs341
Rs2010 = Rs2010
Rs427 = Rs427


Download Source Codes

SerializationWrite.java

SerializationRead.java

Saturday, August 14, 2010

LISP-Like List in Java (Simplified Version)

I have simplified the previous code that I had written for LISP-like list in Java in this post,

Program

import java.util.*;


// To implement LISP-like List in Java to perform functions like car, cdr, cons.

class Lisp
{


public Vector car(Vector v)
{
Vector t = new Vector();
t.addElement(v.elementAt(0));
return t;
}

public Vector cdr(Vector v)
{
Vector t = new Vector();
for(int i=1;i t.addElement(v.elementAt(i));
return t;
}

public Vector cons(String x, Vector v)
{
v.insertElementAt(x,0);
return v;
}

public Vector cons(int x, Vector v)
{
v.insertElementAt(x,0);
return v;
}

}

class Lisp_List2
{
public static void main(String[] args)
{
Lisp a = new Lisp();
Vector v = new Vector(4,1);
Vector v1 = new Vector();

System.out.println("\n Creating a List of Strings....\n");

v.addElement("S.R.Tendulkar");
v.addElement("M.S.Dhoni");
v.addElement("V.Sehwag");
v.addElement("S.Raina");

System.out.println("\n The Contents of the List are " + v);
System.out.print("\n The CAR of this List....");
System.out.println(a.car(v));
System.out.print("\n The CDR of this List....");
v1 = a.cdr(v);

System.out.println(v1);
System.out.println("\n The Contents of this list after CONS..");
v1 = a.cons("Gambhir",v);

System.out.print(" " + v1);

v.removeAllElements();
v1.removeAllElements();

System.out.println("\n\n Creating a List of Integers....\n");

v.addElement(3);
v.addElement(0);
v.addElement(2);
v.addElement(5);

System.out.println("\n The Contents of the List are " + v);
System.out.print("\n The CAR of this List....");
System.out.println(a.car(v));
System.out.print("\n The CDR of this List....");
v1 = a.cdr(v);

System.out.println(v1);
System.out.println("\n The Contents of this list after CONS..");
v1 = a.cons(9,v);

System.out.print(" " + v1);
}
}

Output

Creating a List of Strings....


The Contents of the List are [S.R.Tendulkar, M.S.Dhoni, V.Sehwag, S.Raina]

The CAR of this List....[S.R.Tendulkar]

The CDR of this List....[M.S.Dhoni, V.Sehwag, S.Raina]

The Contents of this list after CONS..
[Gambhir, S.R.Tendulkar, M.S.Dhoni, V.Sehwag, S.Raina]

Creating a List of Integers....


The Contents of the List are [3, 0, 2, 5]

The CAR of this List....[3]

The CDR of this List....[0, 2, 5]

The Contents of this list after CONS..
[9, 3, 0, 2, 5]

Download Source Code

Friday, August 13, 2010

Lisp Like List in Java

Question

Implement Lisp-like list in Java. Write basic operations such as 'car', 'cdr', and 'cons'. If L is a list [3, 0, 2, 5], L.car() returns 3, while L.cdr() returns [0,2,5].


Lisp Operations

Car


The car of a list is, quite simply, the first item in the list. For Ex: car of L.car() of a list [3 0 2 5] returns 3.

Cdr


The cdr of a list is the rest of the list, that is, the cdr function returns the part of the list that follows the first item. For ex: cdr of a list [3 0 2 5] returns [0 2 5]

Cons


The cons function constructs lists. It is useful to add element to the front of the list; it is the inverse of car and cdr. For example, cons can be used to make a five element list from the four element list.

(source – Wikipedia)

Length


Returns the length of the list.


Program


import java.util.*;

import java.io.*;

// To implement LISP-like List in Java to perform functions like car, cdr, cons.

class Lisp

{

Vector v = new Vector(4,1);

int i;

InputStreamReader isr = new InputStreamReader(System.in);

BufferedReader inData = new BufferedReader(isr);

String str;

//Create a LISP-Like List using VECTOR

public void create()

{

int n;

System.out.print("\n Enter the Size of the list:");

//Get Input from the user...Use I/p stream reader for it...

try

{

str = inData.readLine();

n = Integer.parseInt(str);

for(i=0;i

{

int temp;

System.out.print("\n Enter the element " + (i+1) + " of the list:");

str = inData.readLine();

temp=Integer.parseInt(str);

v.addElement(new Integer(temp));

}

}

catch (IOException e)

{

System.out.println("Error!");

System.exit(1);

}

}

//Display the content of LISP-List

public void display()

{

int n=v.size();

System.out.print("[ ");

for(i=0;i

{

System.out.print(v.elementAt(i) + " ");

}

System.out.println("]");

}

/*

The car of a list is, quite simply, the first item in the list.

For Ex: car of L.car() of a list [3 0 2 5] returns 3.

Gives the CAR of LISP-List

*/

public void car()

{

System.out.println("\n CAR of the List: " + v.elementAt(0));

}

/*

The cdr of a list is the rest of the list, that is, the cdr function returns the part of the list that follows the first item.

For ex: cdr of a list [3 0 2 5] returns [0 2 5]

*/

public void cdr()

{

int n=v.size();

System.out.print("\n The CDR of the List is:");

System.out.print("[ ");

for(i=1;i

{

System.out.print(v.elementAt(i) + " ");

}

System.out.println("]");

}

/*

The cons function constructs lists. It is useful to add element to the front of the list; it is the inverse of car and cdr. For example, cons can be used to make a five element list from the four element list.

For ex: adding 7 to [3 0 2 5], cons(7) gives [7 3 0 2 5]

*/

public void cons(int x)

{

v.insertElementAt(x,0);

System.out.print("\n The List after using CONS and adding an element:");

display();

}

// Returns the length of the LISP-List

public int length()

{

return v.size();

}

}

class Lisp_List

{

public static void main(String[] args)

{

Lisp a = new Lisp();

a.create();

System.out.print("\n The contents of the List are:");

a.display();

a.car();

a.cdr();

a.cons(5);

System.out.println("\n\n The length of the list is " + a.length());

}

}


Output


Enter the Size of the list:4

Enter the element 1 of the list:3

Enter the element 2 of the list:0

Enter the element 3 of the list:2

Enter the element 4 of the list:5

The contents of the List are:[ 3 0 2 5 ]

CAR of the List: 3

The CDR of the List is:[ 0 2 5 ]

The List after using CONS and adding an element:[ 5 3 0 2 5 ]

The length of the list is 5


Download the Source Code

Thursday, August 12, 2010

Vehicle Class Hierarchy in Java

Question

Design a Vehicle class hierarchy in Java. Write a test program to demonstrate
polymorphism.

(Program written by Santhosh Kumar S)


Program

import java.util.*;
abstract class Vehicle
{
boolean engstatus=false;
abstract void start();
abstract void moveForward();
abstract void moveBackward();
abstract void applyBrake();
abstract void turnLeft();
abstract void turnRight();
abstract void stop();
}
class Porsche extends Vehicle
{
void truckManufacture()
{
System.out.println("Porsche World Wide Car manufactures ");
}

void gearSystem()
{
System.out.println("\n automatic gearing system.. So don't worry !!");
}
void start()
{
engstatus=true;
System.out.println("\n engine is ON ");
}
void moveForward()
{

if(engstatus==true)
System.out.println("\nCar is moving in forward direction .. Slowly gathering speed ");
else
System.out.println("\n Car is off...Start engine to move");
}
void moveBackward()
{ if(engstatus=true)
System.out.println("\n Car is moving in reverse direction ...");
else
System.out.println("\n Car is off...Start engine to move");
}
void applyBrake()
{
System.out.println("\n Speed is decreasing gradually");
}
void turnLeft()
{
System.out.println("\n Taking a left turn.. Look in the mirror and turn ");
}
void turnRight()
{
System.out.println("\n Taking a right turn.. Look in the mirror and turn ");
}
void stop()
{
engstatus=false;
System.out.println("\n Car is off ");
}
}
class Volvo extends Vehicle
{
void truckManufacture()
{
System.out.println("Volvo Truck Manufactures");
}
void gearSystem()
{
System.out.println("\nManual Gear system...ooops....take care while driving ") ;
}
void start()
{
engstatus=true;
System.out.println("\n engine is ON ");
}
void moveForward()
{

if(engstatus==true)
System.out.println("\n truck is moving in forward direction .. Slowly gathering speed ");
else
System.out.println("\n truck is off...Start engine to move");
}
void moveBackward()
{ if(engstatus=true)
System.out.println("\n truck is moving in reverse direction ...");
else
System.out.println("\n truck is off...Start engine to move");
}
void applyBrake()
{
System.out.println("\n Speed is decreasing gradually");
}
void turnLeft()
{
System.out.println("\n Taking a left turn.. Look in the mirror and turn ");
}
void turnRight()
{
System.out.println("\n Taking a right turn.. Look in the mirror and turn ");
}
void stop()
{
engstatus=false;
System.out.println("\n Truck is off ");
}
}

class Vehicle1
{
public static void main(String[] args)
{
Porsche v1=new Porsche();
v1.truckManufacture();
v1.start();
v1.gearSystem();
v1.moveForward();
v1.applyBrake();
v1.turnLeft();
v1.moveForward();
v1.applyBrake();
v1.turnRight();
v1.moveBackward();
v1.stop();
v1.moveForward();

Volvo v2= new Volvo();
v2.truckManufacture();
v2.start();
v2.gearSystem();
v2.moveForward();
v2.applyBrake();
v2.turnLeft();
v2.moveForward();
v2.applyBrake();
v2.turnRight();
v2.moveBackward();
v2.stop();
v2.moveForward();

}
}

Download the Source Code

Friday, August 6, 2010

Calendar Class in Java

import java.util.Date;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Used to provide an example that exercises most of the functionality of the
* java.util.Calendar Class
* @author Vivek Venkatesh G
* @version
*/
public class CalendarExample {

/**
* Calendar's getTime() method returns a Date Object
* This can then be passed to println() to print today's date (and time) in the traditional format
* @param No parameter for this function
* @return No return value for this function
*/
public static void doCalendarTimeExample()
{
System.out.println("CURRENT DATE/TIME\n\n");
Date now = Calendar.getInstance().getTime();
System.out.println("Calendar.getInstance().getTime():"+ now);
System.out.println();
}

/**
* Simple Date Format from java.text.package
* @param for this no parameter required
*/

public static void doSimpleDateFormat()
{
System.out.println("Simple Date Format \n\n");
// Get Today's Date
Calendar now = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
System.out.println(" It is now :"+ formatter.format(now.getTime()));
System.out.println();
}

/**
* Simple Date difference from java.text.Package
*/
public static void doDataDifference()
{
System.out.println("DIFFERENCE BETWEEN TWO DATES\n\n");
Date startDate1 = new GregorianCalendar(1994,02,14,14,00).getTime();
Date endDate1 = new Date();
long diff = endDate1.getTime() - startDate1.getTime();
System.out.println("Difference between " + endDate1);
System.out.println(" and "+ startDate1 + "is" + (diff/(1000L*60L*60L*24L)) + "days");
System.out.println();
}

public static void doGetMethods()
{
System.out.println("CALENDAR GET METHODS");
Calendar c=Calendar.getInstance();

System.out.println("YEAR : " + c.get(Calendar.YEAR));
System.out.println("MONTH : " + c.get(Calendar.MONTH));
System.out.println("DAY_OF_MONTH : " + c.get(Calendar.DAY_OF_MONTH));
System.out.println("DAY_OF_WEEK : " + c.get(Calendar.DAY_OF_WEEK));
System.out.println("DAY_OF_YEAR : " + c.get(Calendar.DAY_OF_YEAR));
System.out.println("WEEK_OF_YEAR : " + c.get(Calendar.WEEK_OF_YEAR));
System.out.println("WEEK_OF_MONTH : " + c.get(Calendar.WEEK_OF_MONTH));
System.out.println("DAY_OF_WEEK_IN_MONTH : " + c.get(Calendar.DAY_OF_WEEK_IN_MONTH));
System.out.println("HOUR : " + c.get(Calendar.HOUR));
System.out.println("AM_PM : " + c.get(Calendar.AM_PM));
System.out.println("HOUR OF DAY(24-hour) : " + c.get(Calendar.HOUR_OF_DAY));
System.out.println("MINUTE : " + c.get(Calendar.MINUTE));
System.out.println("SECOND : " + c.get(Calendar.SECOND));
System.out.println();

}

public static void main(String[] args)
{
System.out.println();
doCalendarTimeExample();
doSimpleDateFormat();
doDataDifference();
doGetMethods();
}
}


Download the Source Code

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