cse - javalab - cse tube.pdf

Upload: farrukhsharifzada

Post on 14-Jan-2016

244 views

Category:

Documents


0 download

TRANSCRIPT

  • www.c

    setub

    e.in

    1

    CS2309 JAVA LAB

    LAB MANUAL

    III YEAR B.E (COMPUTER SCIENCE AND

    ENGINEERING)

    Prepared by

    S.VARADHARAJAN

    ASSISTANT PROFESSOR

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    2

    CS2309 JAVA LAB L T P C 0 0 3 2

    1. 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 ().

    2. Develop Date class in Java similar to the one available in java.util package. Use JavaDoc

    comments.

    3. 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].

    4. Design a Java interface for ADT Stack. Develop two different classes that implement this

    interface, one using array and the other using linked-list. Provide necessary exception

    handling in both the implementations.

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

    polymorphism.

    6. 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.

    7. Design a scientific calculator using event-driven programming paradigm of Java.

    8. 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.

    9. 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.

    10. Develop multi-threaded echo server and a corresponding GUI client in Java.

    11. [Mini-Project] Develop a programmer's editor in Java that supports syntax highlighting,

    compilation support, debugging support, etc.

    TOTAL= 45

    PERIODS

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    3

    REQUIREMENTS

    HARDWARE:

    Pentium IV with 2 GB RAM,

    160 GB HARD Disk,

    Monitor 1024 x 768 colour

    60 Hz.

    30 Nodes

    SOFTWARE:

    Windows /Linux operating system

    JDK 1.6(or above)

    30 user license

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    4

    TABLE OF CONTENTS

    LIST OF EXPERIMENTS

    1 Rational number

    2 Date class in Java

    3 Implement Lisp-like list in Java.

    4 Java interface for ADT Stack using array and the sing linked-

    list.

    5 Polymorphism

    6 object serialization

    7 scientific calculator

    8

    Multi-threaded Java program

    Fibonacci number (some examples are 2, 3, 5, 13, etc.).

    prime numbers below 100,000 and writes them into a pipe

    Main thread should read both the pipes.

    9 A Simple OPAC system for library

    10 Multi-threaded echo server GUI client.

    11 [Mini-Project] programmers editor.

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    5

    Ex No1: Rational Numbers

    AIM

    To write a Java Program to develop a class for Rational numbers.

    ALGORITHM:

    Step 1:-Declare a class called Rational and invoke a function called gcd(a,b).

    Step 2:-Find out the reminder when a is divided by b and pass it as a parameter to the function.

    Step 3:-Create an object for the class and declare the required string and integer variables.

    Step 4:-Create an object of class DataInputStream .Read the numbers through the ReadLine() method

    into the object.

    Step 5:-Convert the input accepted into Integers through the parseInt method and store them in

    variables a and b.

    Step 6:-store the value returned by the function GCD in variable l.

    Step 7:-Divide a by l and b by l and store them in variables x and y.

    Program:-

    import java.io.*;

    class rational1

    {

    public rational1(){}

    public long gcd(long a,long b)

    {

    if(b==0)

    return a;

    else

    return gcd(b,a%b);

    }

    }

    public class rational

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    6

    {

    public static void main(String args[])throws IOException

    {

    /**

    * create and initialize a new Rational object

    */

    rational1 r=new rational1();

    /**

    * The Numerator and Denominator part of Rational

    */

    long a,b,x,y;

    String str;

    DataInputStream in= new DataInputStream(System.in);

    System.out.println("Enter the value for A");

    str=in.readLine();

    a=Integer.parseInt(str);

    System.out.println("Enter the value for B");

    str=in.readLine();

    b=Integer.parseInt(str);

    long l=r.gcd(a,b);

    System.out.println();

    System.out.println("The GCD of the number is:"+l);

    x=a/l;

    y=b/l;

    System.out.println();

    System.out.println("The resultant value is: "+x+"/"+y);

    }

    }

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    7

    Output

    Enter the value for A

    500

    Enter the value for B

    1000

    The GCD of the number is:500

    The resultant value is: 1/2

    Result

    Thus the above program was executed and verified successfully.

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    8

    Ex No 2: Date Class in Java

    AIM

    To design a Date class in Java.

    ALGORITHM:-

    Step 1: Declare a class called Date example and create an object called date.

    Step 2:- Display the Date and Time through these objects with the Methods in Date Class.

    Step 3:- Declare two objects called start time and end time for this class .

    Step 4:- Create another object called changed object and display the changed time with the calculation

    Step 5:- In the main function create object for the class Date and display the time and date

    accordingly.

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    9

    SOURCE CODE

    import java.util.Date;

    import java.text.ParseException;

    import java.text.SimpleDateFormat;

    public class DateExample {

    private static void DateExample() {

    Date date = new Date();

    System.out.println("Current Date and Time is : " + date);

    System.out.println();

    System.out.println("Date object showing specific date and time");

    Date particulardate1 = new Date(2000,3,12);

    Date particulardate2 = new Date(2000,4,12,9,10);

    System.out.println();

    System.out.println("First Particular date : " + particulardate1);

    System.out.println("Second Particular date: " + particulardate2);

    System.out.println();

    System.out.println("Demo of getTime() method returning milliseconds");

    System.out.println();

    Date strtime = new Date();

    System.out.println("Start Time: " + strtime);

    Date endtime = new Date();

    System.out.println("End Time is: " + endtime);

    long elapsed_time = endtime.getTime() - strtime.getTime();

    System.out.println("Elapsed Time is:" + elapsed_time + "milliseconds");

    System.out.println();

    System.out.println("Changed date object using setTime() method");

    System.out.println();

    Date chngdate = new Date();

    System.out.println("Date before change is: " + chngdate);

    chngdate.setHours(12);

    System.out.println("Now the Changed date is: " + chngdate);

    System.out.println();

    }

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    10

    public static void main(String[] args) {

    System.out.println();

    DateExample();

    }

    }

    OUTPUT

    D:\java>java DateExample

    Current Date and Time is : Thu May 05 09:56:18 IST 2011

    Date object showing specific date and time

    First Particular date : Thu Apr 12 00:00:00 IST 3900

    Second Particular date: Sat May 12 09:10:00 IST 3900

    Demo of getTime() method returning milliseconds

    Start Time: Thu May 05 09:56:18 IST 2011

    End Time is: Thu May 05 09:56:18 IST 2011

    Elapsed Time is:0 milliseconds

    Changed date object using setHours() method

    Date before change is: Thu May 05 09:56:18 IST 2011

    Now the Changed date is: Thu May 05 12:56:18 IST 2011

    Result

    Thus the above program was executed and verified successfully.

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    11

    3.Implement Lisp-like list in Java.

    Aim:

    To Implement basic operations such as 'car', 'cdr', and 'cons' using Lisp-like list in Java. If L is a list

    [3, 0, 2, 5], L.car() returns 3, while L.cdr() returns [0,2,5]

    Procedure:

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    12

    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 list = Arrays.asList(tokenList);

    ArrayList slist = new ArrayList(list);

    slist.remove(0);

    display(slist);

    }

    private void cons(String args) {

    List arrayList = new ArrayList(Arrays.asList(tokenList));

    arrayList.add(args);

    Collections.reverse(arrayList);

    display(arrayList);

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    13

    }

    private void parse(String args) {

    ArrayList tokenList = new ArrayList();

    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();

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    14

    L.cdr();

    L.cons("7");

    }}

    Output:

    Result:

    Thus the above program was executed and verified successfully

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    15

    Ex.No:4 Implementation of Stack ADT

    AIM

    To write a Java Program to design an interface for Stack ADT.and implement Stack ADT

    using both Array and Linked List.

    Procedure:

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    16

    Program:

    public class ADTArray implements ADTStack

    {

    Object[] array;

    int index;

    public ADTArray() {

    this.array = new Object[128];

    this.index = 0;

    }

    //@Override

    public Object pop() {

    index--;

    return array[index];

    }

    //@Override

    public void push(Object item) {

    array[index] = item;

    index++;

    }

    public static void main(String[] args) {

    ADTStack stack = new ADTArray();

    stack.push("Hi");

    stack.push(new Integer(100));

    System.out.println(stack.pop());

    System.out.println(stack.pop());

    }

    }

    public class ADTList implements ADTStack {

    private StackElement top;

    private int count = 0;

    public void push(Object obj) {

    StackElement stackElement = new StackElement(obj);

    stackElement.next = top;

    top = stackElement;

    count++;

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    17

    }

    //@Override

    public Object pop() {

    if (top == null) return null;

    Object obj = top.value;

    top = top.next;

    count--;

    return obj;

    }

    class StackElement {

    Object value;

    StackElement next;

    public StackElement(Object obj) {

    value = obj;

    next = null;

    }

    }

    public static void main(String[] args) {

    ADTStack stack = new ADTList();

    stack.push("Hi");

    stack.push(new Integer(100));

    System.out.println(stack.pop());

    System.out.println(stack.pop());

    }

    }

    public interface ADTStack {

    public void push (Object item);

    public Object pop ();

    }

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    18

    Output:- C:\>java ADTArray 100 Hi C:\>java ADTList 100 Hi C:\>java ADTStack Exception in thread main java.lang.NoSuchMethodError:main

    Result:

    Thus the above program was executed and verified successfully.

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    19

    Ex no: 5 Polymorphism

    Aim:-

    To develop a vehicle class hierarchy in Java to demonstrate the concept of polymorphism.

    Algorithm:-

    Step 1:-Declare a super class called vehicle with data elements doors,wheels and seats.

    Step 2:-Derive another class called car and invoke a function tostring() to display the variables.

    Step 3:-Derive another class called motorcycle with same data and method called setseats() .

    Step 4:-Declare another sub class called Truck with 2 constructors and finally assign values to

    variables.

    Step 5:-In the main function, create an object for class motorcycle and display all details of sub classes

    through object.

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    20

    Sourcecode:-

    //This is the class that will be inherited

    public class Vehicle

    {

    public int doors;

    public int seats;

    public int wheels;

    Vehicle()

    {

    wheels=4;

    doors=4;

    seats=4;

    }

    }

    //This class inherits Vehicle.java

    public class Car extends Vehicle

    {

    public String toString()

    {

    return "This car has "+seats+" Seats, "+doors+" Doors "+

    "and "+wheels+" wheels.";

    }

    }

    //This class inherits Vehicle.java

    public class MotorCycle extends Vehicle

    {

    MotorCycle()

    {

    wheels=2;

    doors=0;

    seats=1;

    }

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    21

    void setSeats(int num)

    {

    seats=num;

    }

    public String toString()

    {

    return "This motorcycle has "+seats+" Seats, "+doors+" Doors "+

    "and "+wheels+" wheels.";

    }

    }

    //This class inherits Vehicle.java

    public class Truck extends Vehicle

    {

    boolean isPickup;

    Truck()

    {

    isPickup=true;

    }

    Truck(boolean aPickup)

    {

    this();

    isPickup=aPickup;

    }

    Truck(int doors, int seats, int inWheels, boolean isPickup)

    {

    this.doors=doors;

    this.seats=seats;

    wheels=inWheels;

    this.isPickup=isPickup;

    }

    public String toString()

    {

    return "This "+(isPickup?"pickup":"truck")+

    " has "+seats+" Seats, "+doors+" Doors "+"and "+wheels+" wheels.";

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    22

    }

    }

    //This class tests the classes that inherit Vehicle.java

    public class VehiclesTest

    {

    public static void main(String args[])

    {

    MotorCycle mine = new MotorCycle();

    System.out.println(mine);

    Car mine2 = new Car();

    System.out.println(mine2);

    mine2.doors=2;

    System.out.println(mine2);

    Truck mine3 = new Truck();

    System.out.println(mine3);

    Truck mine4 = new Truck(false);

    mine4.doors=2;

    System.out.println(mine4);

    }

    }

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    23

    Output

    This motorcycle has 1 Seats, 0 Doors and 2 wheels

    This car has 4 Seats, 4 Doors and 4 wheels

    This car has 4 Seats, 2 Doors and 4 wheels

    This pickup has 4 Seats, 4 Doors and 4 wheels

    This truck has 4 Seats, 2 Doors and 4 wheels

    Result:

    Thus the above program was executed and verified successfully.

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    24

    Ex No:-6 Object Serialization

    Aim:-To write a Java Program to randomly generate objects and write them into a file using concept

    of Object Serialization.

    Algorithm:-

    Step 1:Declare a class called Currency .Open a file in output mode with a name.

    Step 2:-Write new data into the object using writeobject() method.

    Step 3:-Similarly create an input stream object .Read it both in terms of Dollars and Rupees.close the

    output object.

    Step 4:-derive a class called Dollar which implements serializable interface.Invoke a constructor and

    function to display the data.

    Step 5:Similarly declare a class called Rupee with private variables and use print function to display

    the variables.

    Step 6: terminate the execution. The output is displayed as dollar to rupee conversion and vice versa.

    Sourcecode:-

    // Currency conversion

    import java.io.*;

    public class Currency

    {

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    25

    public static void main(String args[])

    {

    Dollar dr=new Dollar('$',40);

    dr.printDollar();

    Rupee re=new Rupee("Rs.",50);

    re.printRupee();

    try

    {

    File f=new File("rd.txt");

    FileOutputStream fos=new FileOutputStream(f);

    ObjectOutputStream oos=new ObjectOutputStream(fos);

    oos.writeObject(dr);

    oos.writeObject(re);

    oos.flush();

    oos.close();

    ObjectInputStream ois=new ObjectInputStream(new FileInputStream("rd.txt"));

    Dollar d1;

    d1=(Dollar)ois.readObject();

    d1.printDollar();

    Rupee r1;

    r1=(Rupee)ois.readObject();

    r1.printRupee();

    ois.close();

    }

    catch(Exception e)

    {

    }

    }

    }

    class Dollar implements Serializable

    {

    private float dol;

    private char sym;

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    26

    public Dollar(char sm,float doll)

    {

    sym=sm;

    dol=doll;

    }

    void printDollar()

    {

    System.out.print(sym);

    System.out.println(dol);

    }

    }

    class Rupee implements Serializable

    {

    private String sym;

    private float rs;

    public Rupee(String sm,float rup)

    {

    sym=sm;

    rs=rup;

    }

    void printRupee()

    {

    System.out.print(sym);

    System.out.println(rs);

    }

    }

    Output:-

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    27

    E:\java>java Currency

    $40.0

    Rs.50.0

    $40.0

    Rs.50.0

    Result:

    Thus the above program was executed and verified successfully.

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    28

    EX NO: 7 Scientific Calculator

    AIM:

    To design a scientific calculator using event-driven programming paradigm of Java.

    ALGORITHM:

    Step1: Define a class CalcFrame for creating a calculator frame and added windolistener to close the

    calculator

    Step2: create instance of object for View menu and various other objects

    Step3: add a listener to receive item events when the state of an item changes

    Step4: Define the methods for all operations of stientific calculator

    Step5::Get the input and display the result

    PROGRAM

    /** Scientific calculator*/

    import java.awt.*;

    import java.awt.event.*;

    // class CalcFrame for creating a calculator frame and added windolistener to

    // close the calculator

    class CalcFrame extends Frame {

    CalcFrame( String str) {

    // call to superclass

    super(str);

    // to close the calculator(Frame)

    addWindowListener(new WindowAdapter() {

    public void windowClosing (WindowEvent we) {

    System.exit(0);

    }

    });

    }

    }

    // main class Calculator implemnets two

    // interfaces ActionListener

    // and ItemListener

    public class Calculator implements ActionListener, ItemListener {

    // creating instances of objects

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    29

    CalcFrame fr;

    TextField display;

    Button key[] = new Button[20]; // creates a button object array of 20

    Button clearAll, clearEntry, round;

    Button scientificKey[] = new Button[10]; // creates a button array of 8

    // declaring variables

    boolean addButtonPressed, subtractButtonPressed, multiplyButtonPressed;

    boolean divideButtonPressed, decimalPointPressed, powerButtonPressed;

    boolean roundButtonPressed = false;

    double initialNumber;// the first number for the two number operation

    double currentNumber = 0; // the number shown in the screen while it is being pressed

    int decimalPlaces = 0;

    // main function

    public static void main (String args[]) {

    // constructor

    Calculator calc = new Calculator();

    calc.makeCalculator();

    }

    public void makeCalculator() {

    // size of the button

    final int BWIDTH = 25;

    final int BHEIGHT = 25;

    int count =1;

    // create frame for the calculator

    fr = new CalcFrame("Scientific Calculator");

    // set the size

    fr.setSize(300,350);

    fr.setBackground(Color.blue);;

    fr.setLayout(null);

    // set the initial numbers that is 1 to 9

    for (int row = 0; row < 3; ++row) {

    for (int col = 0; col < 3; ++col) {

    // this will set the key from 1 to 9

    key[count] = new Button(Integer.toString(count));

    key[count].addActionListener(this);

    // set the boundry for the keys

    key[count].setBounds(30*(col + 1), 30*(row + 4),BWIDTH,BHEIGHT);

    key[count].setBackground(Color.yellow);

    // add to the frame

    fr.add(key[count++]);

    }

    }

    // Now create, addlistener and add to frame all other keys

    //0

    key[0] = new Button("0");

    key[0].addActionListener(this);

    key[0].setBounds(30,210,BWIDTH,BHEIGHT);

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    30

    key[0].setBackground(Color.yellow);

    fr.add(key[0]);

    //decimal

    key[10] = new Button(".");

    key[10].addActionListener(this);

    key[10].setBounds(60,210,BWIDTH,BHEIGHT);

    key[10].setBackground(Color.yellow);

    fr.add(key[10]);

    //equals to

    key[11] = new Button("=");

    key[11].addActionListener(this);

    key[11].setBounds(90,210,BWIDTH,BHEIGHT);

    key[11].setBackground(Color.yellow);

    fr.add(key[11]);

    //multiply

    key[12] = new Button("*");

    key[12].addActionListener(this);

    key[12].setBounds(120,120,BWIDTH,BHEIGHT);

    key[12].setBackground(Color.yellow);

    fr.add(key[12]);

    //divide

    key[13] = new Button("/");

    key[13].addActionListener(this);

    key[13].setBounds(120,150,BWIDTH,BHEIGHT);

    key[13].setBackground(Color.yellow);

    fr.add(key[13]);

    //addition

    key[14] = new Button("+");

    key[14].addActionListener(this);

    key[14].setBounds(120,180,BWIDTH,BHEIGHT);

    key[14].setBackground(Color.yellow);

    fr.add(key[14]);

    //subtract

    key[15] = new Button("-");

    key[15].addActionListener(this);

    key[15].setBounds(120,210,BWIDTH,BHEIGHT);

    key[15].setBackground(Color.yellow);

    fr.add(key[15]);

    //reciprocal

    key[16] = new Button("1/x");

    key[16].addActionListener(this);

    key[16].setBounds(150,120,BWIDTH,BHEIGHT);

    key[16].setBackground(Color.yellow);

    fr.add(key[16]);

    //power

    key[17] = new Button("x^n");

    key[17].addActionListener(this);

    key[17].setBounds(150,150,BWIDTH,BHEIGHT);

    key[17].setBackground(Color.yellow);

    fr.add(key[17]);

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    31

    //change sign

    key[18] = new Button("+/-");

    key[18].addActionListener(this);

    key[18].setBounds(150,180,BWIDTH,BHEIGHT);

    key[18].setBackground(Color.yellow);

    fr.add(key[18]);

    //factorial

    key[19] = new Button("x!");

    key[19].addActionListener(this);

    key[19].setBounds(150,210,BWIDTH,BHEIGHT);

    key[19].setBackground(Color.yellow);

    fr.add(key[19]);

    // CA

    clearAll = new Button("CA");

    clearAll.addActionListener(this);

    clearAll.setBounds(30, 240, BWIDTH+20, BHEIGHT);

    clearAll.setBackground(Color.yellow);

    fr.add(clearAll);

    // CE

    clearEntry = new Button("CE");

    clearEntry.addActionListener(this);

    clearEntry.setBounds(80, 240, BWIDTH+20, BHEIGHT);

    clearEntry.setBackground(Color.yellow);

    fr.add(clearEntry);

    // round

    round = new Button("Round");

    round.addActionListener(this);

    round.setBounds(130, 240, BWIDTH+20, BHEIGHT);

    round.setBackground(Color.yellow);

    fr.add(round);

    // set display area

    display = new TextField("0");

    display.setBounds(30,90,150,20);

    display.setBackground(Color.white);

    // key for scientific calculator

    // Sine

    scientificKey[0] = new Button("Sin");

    scientificKey[0].addActionListener(this);

    scientificKey[0].setBounds(180, 120, BWIDTH + 10, BHEIGHT);

    scientificKey[0].setVisible(true);

    scientificKey[0].setBackground(Color.yellow);

    fr.add(scientificKey[0]);

    // cosine

    scientificKey[1] = new Button("Cos");

    scientificKey[1].addActionListener(this);

    scientificKey[1].setBounds(180, 150, BWIDTH + 10, BHEIGHT);

    scientificKey[1].setBackground(Color.yellow);

    scientificKey[1].setVisible(true);

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    32

    fr.add(scientificKey[1]);

    // Tan

    scientificKey[2] = new Button("Tan");

    scientificKey[2].addActionListener(this);

    scientificKey[2].setBounds(180, 180, BWIDTH + 10, BHEIGHT);

    scientificKey[2].setBackground(Color.yellow);

    scientificKey[2].setVisible(true);

    fr.add(scientificKey[2]);

    // PI

    scientificKey[3] = new Button("Pi");

    scientificKey[3].addActionListener(this);

    scientificKey[3].setBounds(180, 210, BWIDTH + 10, BHEIGHT);

    scientificKey[3].setBackground(Color.yellow);

    scientificKey[3].setVisible(true);

    fr.add(scientificKey[3]);

    // aSine

    scientificKey[4] = new Button("aSin");

    scientificKey[4].addActionListener(this);

    scientificKey[4].setBounds(220, 120, BWIDTH + 10, BHEIGHT);

    scientificKey[4].setBackground(Color.yellow);

    scientificKey[4].setVisible(true);

    fr.add(scientificKey[4]);

    // aCos

    scientificKey[5] = new Button("aCos");

    scientificKey[5].addActionListener(this);

    scientificKey[5].setBounds(220, 150, BWIDTH + 10, BHEIGHT);

    scientificKey[5].setBackground(Color.yellow);

    scientificKey[5].setVisible(true);

    fr.add(scientificKey[5]);

    // aTan

    scientificKey[6] = new Button("aTan");

    scientificKey[6].addActionListener(this);

    scientificKey[6].setBounds(220, 180, BWIDTH + 10, BHEIGHT);

    scientificKey[6].setBackground(Color.yellow);

    scientificKey[6].setVisible(true);

    fr.add(scientificKey[6]);

    // E

    scientificKey[7] = new Button("E");

    scientificKey[7].addActionListener(this);

    scientificKey[7].setBounds(220, 210, BWIDTH + 10, BHEIGHT);

    scientificKey[7].setBackground(Color.yellow);

    scientificKey[7].setVisible(true);

    fr.add(scientificKey[7]);

    // to degrees

    scientificKey[8] = new Button("todeg");

    scientificKey[8].addActionListener(this);

    scientificKey[8].setBounds(180, 240, BWIDTH + 10, BHEIGHT);

    scientificKey[8].setBackground(Color.yellow);

    scientificKey[8].setVisible(true);

    fr.add(scientificKey[8]);

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    33

    // to radians

    scientificKey[9] = new Button("torad");

    scientificKey[9].addActionListener(this);

    scientificKey[9].setBounds(220, 240, BWIDTH + 10, BHEIGHT);

    scientificKey[9].setBackground(Color.yellow);

    scientificKey[9].setVisible(true);

    fr.add(scientificKey[9]);

    fr.add(display);

    fr.setVisible(true);

    } // end of makeCalculator

    public void actionPerformed(ActionEvent ae) {

    String buttonText = ae.getActionCommand();

    double displayNumber = Double.valueOf(display.getText()).doubleValue();

    // if the button pressed text is 0 to 9

    if((buttonText.charAt(0) >= '0') & (buttonText.charAt(0)

  • www.c

    setub

    e.in

    34

    // if button pressed is subtract

    if (buttonText == "-") {

    subtractButtonPressed = true;

    initialNumber = displayNumber;

    currentNumber = 0;

    decimalPointPressed = false;

    }

    // if button pressed is divide

    if (buttonText == "/") {

    divideButtonPressed = true;

    initialNumber = displayNumber;

    currentNumber = 0;

    decimalPointPressed = false;

    }

    // if button pressed is multiply

    if (buttonText == "*") {

    multiplyButtonPressed = true;

    initialNumber = displayNumber;

    currentNumber = 0;

    decimalPointPressed = false;

    }

    // if button pressed is reciprocal

    if (buttonText == "1/x") {

    // call reciprocal method

    display.setText(reciprocal(displayNumber));

    currentNumber = 0;

    decimalPointPressed = false;

    }

    // if button is pressed to change a sign

    //

    if (buttonText == "+/-") {

    // call changesign meyhod to change the

    // sign

    display.setText(changeSign(displayNumber));

    currentNumber = 0;

    decimalPointPressed = false;

    }

    // factorial button

    if (buttonText == "x!") {

    display.setText(factorial(displayNumber));

    currentNumber = 0;

    decimalPointPressed = false;

    }

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    35

    // power button

    if (buttonText == "x^n") {

    powerButtonPressed = true;

    initialNumber = displayNumber;

    currentNumber = 0;

    decimalPointPressed = false;

    }

    // now for scientific buttons

    if (buttonText == "Sin") {

    display.setText(Double.toString(Math.sin(displayNumber)));

    currentNumber = 0;

    decimalPointPressed = false;

    }

    if (buttonText == "Cos") {

    display.setText(Double.toString(Math.cos(displayNumber)));

    currentNumber = 0;

    decimalPointPressed = false;

    }

    if (buttonText == "Tan") {

    display.setText(Double.toString(Math.tan(displayNumber)));

    currentNumber = 0;

    decimalPointPressed = false;

    }

    if (buttonText == "aSin") {

    display.setText(Double.toString(Math.asin(displayNumber)));

    currentNumber = 0;

    decimalPointPressed = false;

    }

    if (buttonText == "aCos") {

    display.setText(Double.toString(Math.acos(displayNumber)));

    currentNumber = 0;

    decimalPointPressed = false;

    }

    if (buttonText == "aTan") {

    display.setText(Double.toString(Math.atan(displayNumber)));

    currentNumber = 0;

    decimalPointPressed = false;

    }

    // this will convert the numbers displayed to degrees

    if (buttonText == "todeg")

    display.setText(Double.toString(Math.toDegrees(displayNumber)));

    // this will convert the numbers display

    // ed to radians

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    36

    if (buttonText == "torad")

    display.setText(Double.toString(Math.toRadians(displayNumber)));

    if (buttonText == "Pi") {

    display.setText(Double.toString(Math.PI));

    currentNumber =0;

    decimalPointPressed = false;

    }

    if (buttonText == "Round")

    roundButtonPressed = true;

    // check if decimal point is pressed

    if (buttonText == ".") {

    String displayedNumber = display.getText();

    boolean decimalPointFound = false;

    int i;

    decimalPointPressed = true;

    // check for decimal point

    for (i =0; i < displayedNumber.length(); ++i) {

    if(displayedNumber.charAt(i) == '.') {

    decimalPointFound = true;

    continue;

    }

    }

    if (!decimalPointFound)

    decimalPlaces = 1;

    }

    if(buttonText == "CA"){

    // set all buttons to false

    resetAllButtons();

    display.setText("0");

    currentNumber = 0;

    }

    if (buttonText == "CE") {

    display.setText("0");

    currentNumber = 0;

    decimalPointPressed = false;

    }

    if (buttonText == "E") {

    display.setText(Double.toString(Math.E));

    currentNumber = 0;

    decimalPointPressed = false;

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    37

    }

    // the main action

    if (buttonText == "=") {

    currentNumber = 0;

    // if add button is pressed

    if(addButtonPressed)

    display.setText(Double.toString(initialNumber + displayNumber));

    // if subtract button is pressed

    if(subtractButtonPressed)

    display.setText(Double.toString(initialNumber - displayNumber));

    // if divide button is pressed

    if (divideButtonPressed) {

    // check if the divisor is zero

    if(displayNumber == 0) {

    MessageBox mb = new MessageBox ( fr, "Error ", true, "Cannot divide by

    zero.");

    mb.show();

    }

    else

    display.setText(Double.toString(initialNumber/displayNumber));

    }

    // if multiply button is pressed

    if(multiplyButtonPressed)

    display.setText(Double.toString(initialNumber * displayNumber));

    // if power button is pressed

    if (powerButtonPressed)

    display.setText(power(initialNumber, displayNumber));

    // set all the buttons to false

    resetAllButtons();

    }

    } // end of action events

    public void itemStateChanged(ItemEvent ie)

    {

    } // end of itemState

    // this method will reset all the button

    // Pressed property to false

    public void resetAllButtons() {

    addButtonPressed = false;

    subtractButtonPressed = false;

    multiplyButtonPressed = false;

    divideButtonPressed = false;

    decimalPointPressed = false;

    powerButtonPressed = false;

    roundButtonPressed = false;

    }

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    38

    public String factorial(double num) {

    int theNum = (int)num;

    if (theNum < 1) {

    MessageBox mb = new MessageBox (fr, "Facorial Error", true,

    "Cannot find the factorial of numbers less than 1.");

    mb.show();

    return ("0");

    }

    else {

    for (int i=(theNum -1); i > 1; --i)

    theNum *= i;

    return Integer.toString(theNum);

    }

    }

    public String reciprocal(double num) {

    if (num ==0) {

    MessageBox mb = new MessageBox(fr,"Reciprocal Error", true,

    "Cannot find the reciprocal of 0");

    mb.show();

    }

    else

    num = 1/num;

    return Double.toString(num);

    }

    public String power (double base, double index) {

    return Double.toString(Math.pow(base, index));

    }

    public String changeSign(double num) {

    return Double.toString(-num);

    }

    }

    class MessageBox extends Dialog implements ActionListener {

    Button ok;

    MessageBox(Frame f, String title, boolean mode, String message) {

    super(f, title, mode);

    Panel centrePanel = new Panel();

    Label lbl = new Label(message);

    centrePanel.add(lbl);

    add(centrePanel, "Center");

    Panel southPanel = new Panel();

    ok = new Button ("OK");

    ok.addActionListener(this);

    southPanel.add(ok);

    add(southPanel, "South");

    pack();

    addWindowListener (new WindowAdapter() {

    public void windowClosing (WindowEvent we) {

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    39

    System.exit(0);

    }

    });

    }

    public void actionPerformed(ActionEvent ae) {

    dispose();

    }

    }

    OUTPUT:

    RESULT:

    Thus a scientific calculator using even-driven programming paradigm of Java is

    developed.

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    40

    EX NO:-8 Multithreading

    Aim:-

    To 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.

    Procedure:

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    41

    Program: import java.io.IOException; import java.io.PipedWriter; public class FibonacciGenerator extends Thread { private PipedWriter fibWriter = new PipedWriter(); public PipedWriter getPipedWriter() { return fibWriter; } @Override public void run() { super.run(); generateFibonacci(); } private int f(int n) { if (n < 2) { return n; } else { return f(n-1)+ f(n-2); } } public void generateFibonacci() { /*do { fibValue = f(i); System.out.println("From Fibo : " + fibValue); try { fibWriter.write(fibValue); } catch (IOException e) { e.printStackTrace(); } i++; } while(fibValue < 10000); */ for (int i = 2, fibValue = 0; (fibValue = f(i)) < 10000; i++) { //System.out.println("From Fibo : " + fibValue); try { fibWriter.write(fibValue); } catch (IOException e) { // TODO Auto-generated catch block

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    42

    e.printStackTrace(); } } //suspend(); } public static void main(String[] args) { new FibonacciGenerator().generateFibonacci(); } }

    import java.io.IOException; import java.io.PipedReader; class Receiver extends Thread { private PipedReader fibReader; private PipedReader primeReader; public Receiver(FibonacciGenerator fib, PrimeGenerator prime) throws IOException { fibReader = new PipedReader(fib.getPipedWriter()); primeReader = new PipedReader(prime.getPipedWriter()); } public void run() { int prime = 0; int fib = 0; try { prime = primeReader.read(); fib = fibReader.read(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } while (true) { //System.out.println("FROM PRIME PIPE ::" + prime); //System.out.println("FROM FIB PIPE::" + fib); try { if (prime == fib) { System.out.println("MATCH ::" + prime); prime = primeReader.read(); fib = fibReader.read(); } else if (fib < prime) { fib = fibReader.read(); } else { prime = primeReader.read(); } } catch (IOException e) {

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    43

    System.exit(-1); } } } }

    import java.io.IOException; import java.io.PipedWriter; public class PrimeGenerator extends Thread { private PipedWriter primeWriter = new PipedWriter(); public PipedWriter getPipedWriter() { return primeWriter; } @Override public void run() { super.run(); generatePrime(); } public void generatePrime() { for (int i = 2; i < 10000; i++) { if (isPrime(i)) { try { //System.out.println("From Prime : " + i); primeWriter.write(i); } catch (IOException e) { e.printStackTrace(); } } } //suspend(); } private boolean isPrime(int n) { boolean prime = true; int sqrtValue = (int) Math.sqrt(n); for (int i = 2; i

  • www.c

    setub

    e.in

    44

    return prime; } public static void main(String[] args) throws IOException { PrimeGenerator gene = new PrimeGenerator(); gene.generatePrime(); } }

    import java.io.IOException; public class Main { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { FibonacciGenerator fibonacciGenerator = new FibonacciGenerator(); PrimeGenerator primeGenerator = new PrimeGenerator(); Receiver receiver = new Receiver(fibonacciGenerator, primeGenerator); fibonacciGenerator.start(); primeGenerator.start(); receiver.start(); /*fibonacciGenerator.stop(); primeGenerator.stop(); receiver.stop();*/ //fibonacciGenerator.run(); } }

    Output:

    C:\jdk1.5\bin>javac FibonacciGenerator.java

    C:\jdk1.5\bin>javac PrimeGenerator.java

    C:\jdk1.5\bin>javac Receiver.java

    C:\jdk1.5\bin>javac Main.java

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    45

    MATCH ::2

    MATCH ::3

    MATCH ::5

    MATCH ::13

    MATCH ::89

    MATCH ::233

    MATCH ::1597

    C:\jdk1.5\bin>

    Result:

    Thus the above program was executed and verified successfully.

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    46

    Ex.No: 9 A Simple OPAC system for library

    Aim:-

    To develop a simple OPAC System for library management system using event-driven and

    concurrent programming paradigms and java database connectivity.

    Algorithm:-

    Step 1:Initiate a class and declare the driver for the Driver name required to connect to the database.

    Step 2:-Enclose the coding in a try block to handle errors and trap the exception in a catch block.

    Step 3:-Establish the connection object to connect to the backend.

    Step 4:-Create an object for Statement object using createStatement() object.

    Step 5:-Issue a query through executeQuery() method.

    Program

    import java.sql.*;

    import java.awt.*;

    import java.awt.event.*;

    import javax.swing.*;

    public class Datas extends JFrame implements ActionListener {

    JTextField id;

    JTextField name;

    JButton next;

    JButton addnew;

    JPanel p;

    static ResultSet res;

    static Connection conn;

    static Statement stat;

    public Datas()

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    47

    {

    super("Our Application");

    Container c = getContentPane();

    c.setLayout(new GridLayout(5,1));

    id = new JTextField(20);

    name = new JTextField(20);

    next = new JButton("Next BOOK");

    p = new JPanel();

    c.add(new JLabel("ISBN",JLabel.CENTER));

    c.add(id);

    c.add(new JLabel("Book Name",JLabel.CENTER));

    c.add(name);

    c.add(p);

    p.add(next);

    next.addActionListener(this);

    pack();

    setVisible(true);

    addWindowListener(new WIN());

    }

    public static void main(String args[]) {

    Datas d = new Datas();

    try {

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

    conn = DriverManager.getConnection("jdbc:odbc:custo"); // cust is the DSN Name

    stat = conn.createStatement();

    res = stat.executeQuery("Select * from stu"); // Customers is the table name

    res.next();

    }

    catch(Exception e) {

    System.out.println("Error" +e);

    }

    d.showRecord(res);

    }

    public void actionPerformed(ActionEvent e) {

    if(e.getSource() == next) {

    try {

    res.next();

    }

    catch(Exception ee) {}

    showRecord(res);

    }

    }

    public void showRecord(ResultSet res) {

    try {

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    48

    id.setText(res.getString(2));

    name.setText(res.getString(3));

    }

    catch(Exception e) {}

    }//end of the main

    //Inner class WIN implemented

    class WIN extends WindowAdapter {

    public void windowClosing(WindowEvent w) {

    JOptionPane jop = new JOptionPane();

    jop.showMessageDialog(null,"Database","Thanks",JOptionPane.QUESTION_MESSAGE);

    }

    } } //end of the class

    Output:

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    49

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    50

    Concurrent

    import java.sql.*;

    import java.sql.DriverManager.*;

    class Ja

    {

    String bookid,bookname;

    int booksno;

    Connection con;

    Statement stmt;

    ResultSet rs;

    Ja()

    {

    try

    {

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

    con=DriverManager.getConnection("jdbc:odbc:co");

    }

    catch(Exception e)

    {

    System.out.println("connection error");

    }

    }

    void myput()

    {

    try

    {

    stmt=con.createStatement();

    rs=stmt.executeQuery("SELECT * FROM opac");

    while(rs.next())

    {

    booksno=rs.getInt(1);

    bookid=rs.getString(2);

    bookname=rs.getString(3);

    System.out.println("\n"+ booksno+"\t"+bookid+"\t"+bookname);

    }

    rs.close();

    stmt.close();

    con.close();

    }

    catch(SQLException e)

    {

    System.out.println("sql error");

    }

    }

    }

    class prog1

    {

    public static void main(String arg[])

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    51

    {

    Ja j=new Ja();

    j.myput();

    }

    }

    Output:

    Result:

    Thus the above program was executed and verified successfully.

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    52

    Ex.No: 10 Multi-threaded echo server GUI clients

    Aim:-

    To develop a Java Program that supports multithreaded echo server and a GUI client.

    Procedure:

    Program:

    /**************PROGRAM FOR MULTI-THREADED ECHO SERVER********************/

    /******************************* chatclient .java**********************************/

    import java.awt.*;

    import java.awt.event.*;

    import java.io.*; import java.net.*;

    class chatclient extends Frame implements ActionListener,Runnable

    {

    TextArea ta;

    TextField tf;

    BufferedReader br;

    PrintWriter pw;

    public static void main(String args[])

    {

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    53

    chatclient cc=new chatclient("ChatClient",args[0],4040);

    cc.show();

    cc.setSize(300,400);

    }

    chatclient(String title,String address,int port)

    {

    super(title);

    addWindowListener(new WindowAdapter()

    {

    public void windowClosing(WindowEvent we)

    {

    System.exit(0);

    }

    }

    );

    ta=new TextArea(10,60);

    ta.setEditable(false);

    add(ta,BorderLayout.CENTER);

    tf=new TextField(" ",10);

    tf.addActionListener(this);

    add(tf,BorderLayout.SOUTH);

    try

    {

    Socket s=new Socket(address,port);

    InputStream is=s.getInputStream();

    InputStreamReader isr=new InputStreamReader(is);

    br=new BufferedReader(isr);

    OutputStream os=s.getOutputStream();

    pw=new PrintWriter(os,true);

    }

    catch(Exception e)

    {

    System.out.println(e);

    }

    Thread thread=new Thread(this);

    thread.start();

    }

    public void actionPerformed(ActionEvent ae)

    {

    try { String str=tf.getText();

    pw.println(str); tf.setText(" ");

    }

    catch(Exception e)

    {

    System.out.println(e);

    }

    }

    public void run()

    {

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    54

    try

    {

    while(true)

    {

    String str=br.readLine();

    ta.append(str+"\n");

    }

    }

    catch(Exception e)

    {

    System.out.println(e);

    }

    }

    }

    /*************************** chatserver.java***********************************/

    import java.net.*;

    import java.util.*;

    class chatserver

    {

    static Vector serverthreads;

    public static void main(String args[])

    {

    try

    {

    serverthreads=new Vector();

    ServerSocket ss=new ServerSocket(4040);

    while(true)

    {

    Socket s=ss.accept();

    serverthread st=new serverthread(s);

    st.start();

    serverthreads.addElement(st);

    }

    }

    catch(Exception e)

    {

    System.out.println(e);

    }

    }

    public synchronized static void echoAll(String str)

    {

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    55

    Enumeration e=serverthreads.elements();

    while(e.hasMoreElements())

    {

    try

    {

    serverthread st=(serverthread)e.nextElement();

    st.echo(str);

    }

    catch(Exception ae)

    {

    System.out.println(ae);

    }

    }

    }

    }

    /****************************** serverthread.java*********************************/

    import java.io.*;

    import java.net.*;

    class serverthread extends Thread

    {

    private BufferedReader br;

    private PrintWriter pw;

    public serverthread(Socket socket)

    {

    try

    {

    InputStream is=socket.getInputStream();

    InputStreamReader isr=new InputStreamReader(is);

    br=new BufferedReader(isr); OutputStream os=socket.getOutputStream();

    pw=new PrintWriter(os,true);

    }

    catch(Exception e)

    {

    System.out.println(e);

    }

    }

    public void run()

    {

    try

    {

    while(true)

    {

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    56

    String str=br.readLine();

    chatserver.echoAll(str);

    }

    }

    catch(Exception e)

    {

    System.out.println(e);

    }

    }

    public void echo(String str)

    {

    try

    {

    pw.println(str);

    }

    catch(Exception e)

    {

    System.out.println(e);

    }

    }

    }

    OUTPUT:

    D:\ Java\jdk1.5.0_03\bin>javac ServerThread.java

    D:\ Java\jdk1.5.0_03\bin>javac chatserver.java

    D:\Java\jdk1.5.0_03\bin>java chatserver

    D:\Java\jdk1.5.0_03\bin>javac chatclient.java

    D:\Java\jdk1.5.0_03\bin>java chatclient 192.168.15.143

    D:\Java\jdk1.5.0_03\bin>java chatclient 192.168.15.143

    D:\Java\jdk1.5.0_03\bin>java chatclient 192.168.15.143

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    57

    Result:

    Thus the above program was executed and verified successfully.

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    58

    MiniProject

    Aim:

    To Develop a programmer's editor in Java that supports syntax highlighting,

    compilation support, debugging support, etc

    Program:

    /*********************** PROGAMMERS EDITOR IN JAVA************************/ /* Client Frame Design with width=600 & height=500*/

    import java.awt.Color;

    import java.awt.event.ActionEvent;

    import java.awt.event.ActionListener;

    import java.awt.event.MouseEvent;

    import java.awt.event.MouseListener;

    import java.awt.event.MouseMotionListener;

    import java.awt.event.WindowAdapter;

    import java.awt.event.WindowEvent;

    import java.awt.event.WindowListener;

    import java.io.BufferedReader;

    import java.io.File;

    import java.io.FileInputStream;

    import java.io.FileOutputStream;

    import java.io.FileReader;

    import java.io.InputStreamReader;

    import javax.swing.*;

    import javax.swing.border.Border;

    import javax.swing.text.Element;

    import java.util.StringTokenizer;

    public class Client implements ActionListener,MouseListener,MouseMotionListener

    {

    /************ Components *****************/

    JFrame frame;

    JTextArea jta1;

    public JTextArea jta2;

    JTextArea jta3;

    JButton jb1;

    JButton jb2;

    JButton jb3;

    JButton jb4;

    JLabel jl1;

    JLabel jl2;

    JLabel jl3;

    JScrollPane jsp1;

    JScrollPane jsp2;

    JScrollPane jsp3;

    JTabbedPane jtp1;

    JTabbedPane jtp2;

    JTabbedPane jtp3;

    JMenuBar jm;

    JMenu open;

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    59

    JMenu exit;

    JMenu file;

    JMenu help;

    JMenu compile;

    JMenu run;

    JMenu opt;

    /************ Variables *****************/

    String line;

    String option;

    String className;

    String pureFile;

    File f2;

    File f3;

    public Client()

    {

    frame=new JFrame("XDoS Compiler");

    frame.setLayout(null);

    frame.setBounds(300,10,200,200);

    frame.setSize(900,650);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    jta1=new JTextArea(300,400);

    jsp1=new JScrollPane(jta1);

    jsp1.setBounds(10, 10, 670, 200);

    jsp1.setEnabled(false);

    Border etchedBdr1 = BorderFactory.createEtchedBorder();

    jta1.setBorder(etchedBdr1); //frame.add(jsp1);

    jta2=new JTextArea(300,400);

    jsp2=new JScrollPane(jta2);

    jsp2.setBounds(10, 280, 670, 150);

    Border etchedBdr2 = BorderFactory.createEtchedBorder();

    jta2.setBorder(etchedBdr2);

    jta2.setEditable(false);

    //frame.add(jsp2);

    jta3=new JTextArea(300,400);

    jsp3=new JScrollPane(jta3);

    jsp3.setBounds(10, 450, 670, 150);

    Border etchedBdr3 = BorderFactory.createEtchedBorder();

    jta3.setBorder(etchedBdr3);

    //frame.add(jsp3);

    jl1=new JLabel();

    jl1.setBounds(500, 380, 670, 150);

    frame.add(jl1);

    jl2=new JLabel();

    jl2.setBounds(550, 380, 670, 150);

    frame.add(jl2); jl3=new JLabel();

    jl3.setBounds(600, 380, 670, 150);

    frame.add(jl3);

    jb1=new JButton("Browse");

    jb1.setBounds(50, 235, 100, 20);

    jb1.addActionListener(this);

    //frame.add(jb1);

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    60

    jb2=new JButton("compile");

    jb2.setBounds(200, 235, 100, 20);

    jb2.addActionListener(this);

    //frame.add(jb2); jb3=new JButton("Send");

    jb3.setBounds(550, 235, 100, 20);

    jb3.addActionListener(this);

    //frame.add(jb3);

    jb4=new JButton("Run");

    jb4.setBounds(400, 235, 100, 20);

    jb4.addActionListener(this);

    //frame.add(jb4);

    jtp1=new JTabbedPane();

    jtp1.addTab( "untitled.java", jsp1 );

    jtp1.setBounds(10, 40, 670, 400);

    UIManager.put("TabbedPane.selected", Color.green);

    jtp1.set ForegroundAt(0,Color.BLUE);

    jtp1.setBackgroundAt(0,Color.BLUE);

    frame.add(jtp1); jtp2=new JTabbedPane();

    jtp2.addTab( "Result", jsp2 );

    jtp2.setBounds(10, 450, 670, 150);

    frame.add(jtp2); jtp3=new JTabbedPane();

    jtp3.addTab( "Reply", jsp3 );

    jtp3.setBounds(700, 40, 180, 560);

    frame.add(jtp3); jm=new JMenuBar();

    file=new JMenu("File");

    file.setMnemonic('F');

    opt=new JMenu("Option");

    opt.setMnemonic('O');

    opt.setEnabled(false);

    jm.add(file);

    jm.add(opt);

    compile=new JMenu("Compile");

    compile.setMnemonic('C');

    Action action3 = new AbstractAction("Compile")

    {

    public void actionPerformed(ActionEvent e)

    {

    compile();

    }

    };

    JMenuItem item3 = file.add(action3);

    opt.add(item3);

    run=new JMenu("Run");

    run.setMnemonic('R');

    Action action4 = new AbstractAction("Run")

    {

    public void actionPerformed(ActionEvent e)

    {

    run();

    }

    };

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    61

    JMenuItem item4 = file.add(action4);

    opt.add(item4); help=new JMenu("Help");

    jm.add(help); open=new JMenu("open");

    Action action1 = new AbstractAction("Open")

    {

    public void actionPerformed(ActionEvent e)

    { open(); } };

    JMenuItem item1 = file.add(action1);

    file.add(item1); exit=new JMenu("Exit");

    Action action2 = new AbstractAction("Exit")

    {

    public void actionPerformed(ActionEvent e)

    {

    System.exit(0); } };

    JMenuItem item2 = file.add(action2);

    file.add(item2);

    jm.setBounds(5, 0, 880, 30);

    frame.add(jm);

    frame.setResizable(false);

    frame.setVisible(true);

    jta1.addMouseListener(this);

    jta1.addMouseMotionListener(this);

    jtp1.addMouseListener(this); jtp2.addMouseListener(this);

    }

    public void mouseClicked(MouseEvent ew)

    {

    if(ew.getSource()==jta1)

    {

    jl3.setText("Line-No: "+Integer.toString(getCurrentLineNumber()));

    }

    else if(ew.getSource()==jtp2)

    {

    if(jtp1.isShowing())

    {

    frame.remove(jtp1);

    jtp2.setBounds(10, 40, 670, 560);

    jl1.setBounds(500, 535, 670, 150);

    jl2.setBounds(550, 535, 670, 150);

    jl3.setBounds(600, 535, 670, 150);

    jta2.addMouseMotionListener(this);

    jl3.setText("Line-No: "+Integer.toString(getCurrentLineNumber()));

    }

    else { frame.add(jtp1);

    jtp2.setBounds(10, 450, 670, 150);

    jl1.setBounds(500, 380, 670, 150);

    jl2.setBounds(550, 380, 670, 150);

    jl3.setBounds(600, 380, 670, 150);

    jta2.removeMouseMotionListener(this);

    } }

    else if(ew.getSource()==jtp1)

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    62

    {

    if(jtp2.isShowing())

    { frame.remove(jtp2);

    frame.remove(jtp3); jtp1.setBounds(10, 40, 870, 560);

    jl1.setBounds(500, 535, 670, 150);

    jl2.setBounds(550, 535, 670, 150);

    jl3.setBounds(600, 535, 670, 150);

    }

    else { frame.add(jtp2); frame.add(jtp3);

    jtp1.setBounds(10, 40, 670, 400);

    jl1.setBounds(500, 380, 670, 150);

    jl2.setBounds(550, 380, 670, 150);

    jl3.setBounds(600, 380, 670, 150); } } }

    public void mouseEntered(MouseEvent ew)

    {} public void mouseExited(MouseEvent ew) {}

    public void mousePressed(MouseEvent ew) {}

    public void mouseReleased(MouseEvent ew) {}

    public void mouseMoved(MouseEvent e)

    { jl1.setText("X-: "+Integer.toString(e.getX()));

    jl2.setText("Y-: "+Integer.toString(e.getY())); }

    public void mouseDragged(MouseEvent e) {}

    public void actionPerformed(ActionEvent ae) {}

    public void open()

    {

    JFileChooser fileChooser = new JFileChooser();

    fileChooser.addChoosableFileFilter(new MyFilter());

    int select=fileChooser.showOpenDialog(frame);

    if(select==JFileChooser.APPROVE_OPTION) {

    File file=fileChooser.getSelectedFile();

    String filename=fileChooser.getSelectedFile().getName();

    try { FileInputStream fis=new FileInputStream(file);

    int n=fis.available(); byte dat[]=new byte[n];

    fis.read(dat); String data=new String(dat);

    jtp1.setTitleAt(0, filename);

    jta1.setText(data); opt.setEnabled(true); }

    catch(Exception e)

    { e.printStackTrace(); } }

    }

    public int getCurrentLineNumber()

    {

    int line;

    int caretPosition = jta1.getCaretPosition();

    Element root = jta1.getDocument().getDefaultRootElement();

    line = root.getElementIndex(caretPosition) + 1; return line;

    }

    public void compile() { try { jtp2.setTitleAt(0,"Compile");

    String ta1=jta1.getText().trim();

    StringBuffer sb=new StringBuffer(ta1);

    int id1=ta1.indexOf("public class");

    int id2=ta1.indexOf(" ",id1+13);

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    63

    String name=ta1.substring(id1, id2).trim();

    StringTokenizer st3=new StringTokenizer(name,"\n");

    System.out.println(st3.countTokens());

    String word=st3.nextToken().toString().trim(); System.out.println(word+"*");

    StringTokenizer st4=new StringTokenizer(word," "); System.out.println(st4.countTokens());

    st4.nextToken(); st4.nextToken();

    pureFile=st4.nextToken().toString().trim();

    className=pureFile+".java"; //System.out.println(st4.nextElement().toString().trim()+"*");

    FileOutputStream f=new FileOutputStream(className);

    f.write(ta1.getBytes());

    f.close();

    f2=new File(className); f3=new File(pureFile+".class");

    System.out.println(f2.getAbsolutePath());

    String path=f2.getAbsolutePath(); int a1=path.indexOf("\\");

    int a2=path.lastIndexOf("\\");

    System.out.println(a1+" "+a2);

    String colan=path.substring(0, a1).trim();

    String location=path.substring(0, a2+1).trim();

    System.out.println(colan);

    System.out.println(location);

    compiler(className); }

    catch (Exception err)

    { err.printStackTrace();

    } //option=JOptionPane.showInputDialog(null,"Enter Destination System

    Name","Destination",1).toString(); //System.out.println(option); // jta2.setText(line); }

    public void run() { jtp2.setTitleAt(0,"Run");

    runer(pureFile); }

    public static void main(String args[])

    {

    try

    {

    UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");

    }

    catch (Exception e) { } new Client(); }

    public void compiler(String name)

    { try { jta2.setText("");

    jta2.append("Compilation Started.....\n");

    jta2.append("Proceed.....\n");

    jta2.setForeground(Color.blue);

    String callAndArgs= "cmd /c compile.bat "+name; Process p =Runtime.getRuntime().exec(callAndArgs);

    BufferedReader br=new BufferedReader(new InputStreamReader(p.getInputStream()));

    String str=br.readLine();

    while(str!=null)

    {

    System.out.println(str);

    str=br.readLine(); }

    File f1 = new File("error.txt");

    FileReader fr = new FileReader(f1);

    BufferedReader br1 = new BufferedReader(fr);

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    64

    StringBuffer sb1 = new StringBuffer();

    String eachLine = br1.readLine();

    while (eachLine != null)

    {

    jta2.setForeground(Color.RED);

    sb1.append(eachLine);

    sb1.append("\n");

    eachLine= br1.readLine(); }

    jta2.append(sb1.toString());

    //input.close(); if(f1.length()==0)

    {

    jta2.append("Compiled Successfully........\n");

    jta2.append("Done........"); } } catch(Exception e)

    { e.printStackTrace(); } }

    public void runer(String name)

    {

    try { jta3.setText("");

    String callAndArgs= "cmd /c run.bat "+name;

    Process p =Runtime.getRuntime().exec(callAndArgs);

    BufferedReader br=new BufferedReader(new InputStreamReader(p.getInputStream())); String

    str=br.readLine(); while(str!=null)

    {

    System.out.println(str); str=br.readLine();

    }

    File f1 = new File("output.txt");

    FileReader fr = new FileReader(f1);

    BufferedReader br1 = new BufferedReader(fr);

    StringBuffer sb1 = new StringBuffer();

    String eachLine = br1.readLine();

    while (eachLine != null)

    {

    sb1.append(eachLine);

    sb1.append("\n");

    eachLine = br1.readLine();

    }

    String sp=sb1.toString();

    StringBuffer st=new StringBuffer(sp);

    System.out.println(st.length()); int indx=sp.indexOf(">"); int r=1;

    while(indx != -1)

    {

    System.out.println(Integer.toString(indx)+"*");

    System.out.println(st);

    st.insert(indx+r, "\n");

    indx=sp.indexOf(">",indx+1);

    r++;

    System.out.println(Integer.toString(indx)+"#");

    }

    jta2.setText(st.toString()); f2.deleteOnExit();

    f3.deleteOnExit(); }

    catch(Exception e)

    { e.printStackTrace(); } } }

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    65

    class MyFilter extends javax.swing.filechooser.FileFilter

    {

    public boolean accept(File file)

    {

    return file.isDirectory() || file.getName().endsWith(".java");

    }

    public String getDescription()

    { return "*.java"; } }

    /* Test Frame Design */

    import javax.swing.*;

    import java.awt.*;

    public class Test {

    public Test() { JFrame f = new JFrame("Test");

    f.setLayout(new FlowLayout());

    JTextField jt1 = new JTextField(25);

    f.add(jt1); f.setVisible(true);

    f.setSize(200,200);

    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    public static void main(String args[])

    {

    new Test();

    }

    }

    OUTPUT:

    D:\ Java\jdk1.5.0_03\bin>javac Client.java

    D:\ Java\jdk1.5.0_03\bin>javac Test.java

    D:\ Java\jdk1.5.0_03\bin>java Test

    D:\ Java\jdk1.5.0_03\bin>java Client

    www.csetube.in

    www.csetube.in

  • www.c

    setub

    e.in

    66

    Result:

    Thus the above program was executed and verified successfully.

    www.csetube.in

    www.csetube.in