0% found this document useful (0 votes)
65 views49 pages

EIT Practical File (28200109)

The document contains the practical file submitted by Gaurav for the EIT lab in Computer Science & Engineering Department at Panipat Institute of Engineering & Technology, Samalkha, Panipat. It includes 10 programs implemented by Gaurav related to data structures, object-oriented programming and servlets. The file contains an index listing the programs with details like practical name, date and page number. Each program is explained with code snippets and output.

Uploaded by

Ledna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views49 pages

EIT Practical File (28200109)

The document contains the practical file submitted by Gaurav for the EIT lab in Computer Science & Engineering Department at Panipat Institute of Engineering & Technology, Samalkha, Panipat. It includes 10 programs implemented by Gaurav related to data structures, object-oriented programming and servlets. The file contains an index listing the programs with details like practical name, date and page number. Each program is explained with code snippets and output.

Uploaded by

Ledna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 49

Panipat Institute of Engineering &

Technology, Samalkha, Panipat

Computer Science & Engineering Department

Practical File- EIT Lab

(PC-CS309LA)

2021-2022

Submitted to:- Submitted by:-


Mr. Gaurav Gambhir Gaurav
(AP CSE) 2820109

B.Tech CSE 3A
INDEX

S.NO. Practical Name Date Page Signature


No.

1. Write a Java Package with Stack and queue 16/09/2022


classes.

2. Design a class for Complex numbers in 16/10/2022


Java .In addition to methods for basic
operations on complex numbers,
provide a method to return the number
of active objects created.
3. Develop with suitable hierarchy, class 30/09/2022
for point, shape rectangle, square, circle,
ellipse, triangle, polygenetic.

4. Design a simple test application to 30/09/2022


demonstrate dynamic polymorphism.

5. Design a java interface for ADT Stack. 14/10/2022

6. Develop two different classes that 14/10/2022


implement this interface. One using
array and other using linked list.

7. Develop a simple paint like program that 11/11/2022


can draw basic graphical primitives.

[i]
INDEX

S.NO. Practical Name Date Page Signature


No.

8. Develop a scientific calculator using event 11/11/2022


driven programming.

9. Develop a template for linked list class 02/12/22


along with its members in Java.

10. Write a program to insert and view data 02/12/22


using Servlets.

[ii]
Gaurav 2820109

PROGRAM NO. - 1

Write a Java Package with Stack and queue classes.

Program(Stack):-

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

class Main
{

static void stack_push(Stack<Integer> stack)


{
for(int i = 0; i < 5; i++)
{
stack.push(i);
}
}

static void stack_pop(Stack<Integer> stack)


{
System.out.println("\n\nGaurav -- 2820109\n");
System.out.println("Hello World");
System.out.println("Pop Operation:");

for(int i = 0; i < 5; i++)


{
Integer y = (Integer) stack.pop();
System.out.println(y);
}
}

static void stack_peek(Stack<Integer> stack)


{
Integer element = (Integer) stack.peek();
System.out.println("Element on stack top: " + element);
}

static void stack_search(Stack<Integer> stack, int element)


{
Integer pos = (Integer) stack.search(element);

if(pos == -1)
1
Gaurav 2820109

System.out.println("Element not found");


else
System.out.println("Element is found at position: " + pos);
}

public static void main (String[] args)


{
Stack<Integer> stack = new Stack<Integer>();

stack_push(stack);
stack_pop(stack);
stack_push(stack);
stack_peek(stack);
stack_search(stack, 2);
stack_search(stack, 6);
}
}

2
Gaurav 2820109

Output: -

Program(Queue):-

import java.util.*;
class QueueDemo{

3
Gaurav 2820109

public static void main(String args[]){

System.out.println("\n\nGaurav -- 2820109\n");

PriorityQueue<String> queue=new PriorityQueue<String>();


queue.add("Gaurav");
queue.add("Mayur");
queue.add("Akash");
queue.add("Rohit");
queue.add("Agnivarat");

System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
System.out.println("iterating the queue elements:");
Iterator itr=queue.iterator();

while(itr.hasNext()){
System.out.println(itr.next());
}

queue.remove();
queue.poll();

System.out.println("after removing two elements:");


Iterator<String> itr2=queue.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());

}
}
}

Output: -

4
Gaurav 2820109

PROGRAM NO. – 2

Design a class for Complex numbers in Java .In addition to methods for basic
operations on complex numbers, provide a method to return the number of active
5
Gaurav 2820109

objects created.

class complex
{
double real;
double imag;
public complex(double real, double imag)
{
this.real=real;
this.imag=imag;
}
public static void main(String args[]) {
System.out.println(“\n\nGaurav -- 2820109\n”);
complex n1 = new complex(2.3, 4.5);
complex n2 = new complex(3.4, 5.0);
complex temp;
temp = add(n1, n2);
System.out.printf("Sum = %.1f + %.1fi", temp.real, temp.imag);
}

public static complex add(complex n1, complex n2)


{
complex temp = new complex(0.0, 0.0);

temp.real = n1.real + n2.real;


temp.imag = n1.imag + n2.imag;

return(temp);
}

}
Output: -

6
Gaurav 2820109

PROGRAM NO. - 3

Develop with suitable hierarchy, class for point, shape rectangle, square, circle,
ellipse, triangle, polygenetic.

class Shape {
String shapeVar="This automatically tells the shape";
int lengthOfSide1=0, lengthOfSide2=0;
final double PI=3.14;
7
Gaurav 2820109

void calcArea(){
System.out.print("This method will calculate the area of the shape
selected\n");
}

void setShape(String str){


shapeVar=str;
}

void setSides(int side){


lengthOfSide1=side;
}

void setSides(int side, int side2){


lengthOfSide1=side;
lengthOfSide2=side2;
}

public static void main(String[] args){


System.out.println("\n\nGaurav -- 2820109\n");
Shape obj;
obj=new rectangle();
obj.calcArea();
}

// POINT
class point extends Shape{

point(){
setShape("Point represents a dimensionless shape");
}

void calcArea(){

8
Gaurav 2820109

System.out.print("It doesn't make sense to calculate area of point\n");


}

void getSides(){
System.out.print("No of sides in point is : infinite\n");
}
}

// RECTANGLE
class rectangle extends Shape{

rectangle(){
setShape("A rectangle is closed flat shape, having four sides, and each
angle equal to 90 degrees. The opposite sides of the rectangle are equal and
parallel.");
}

void calcArea(){
setSides(6, 7);
System.out.print("Area is: "+lengthOfSide1*lengthOfSide2);
}

void getSides(){
System.out.print("No of sides in point is :"+4+"\n");
}
}

// SQUARE
class square extends Shape{

square(){
setShape("Square is a plane figure with four equal sides and four right
(90°) angles. A square is a special kind of rectangle (an equilateral one) and a
special kind of parallelogram (an equilateral and equiangular one).");
}

void calcArea(){
9
Gaurav 2820109

setSides(8);
System.out.print("Area is: "+lengthOfSide1*lengthOfSide1);
}

void getSides(){
System.out.print("No of sides in point is : "+4+"\n");
}
}

// CIRCLE
class circle extends Shape{

circle(){
setShape("A circle is a round-shaped figure that has no corners or edges.");
}

void calcArea(){
setSides(8);
System.out.print("Area is: "+PI*lengthOfSide1*lengthOfSide1);
}

void getSides(){
System.out.print("No of sides in point is : infinite\n");
}
}

// ELLIPSE
class ellipse extends Shape{

ellipse(){
setShape("An ellipse is a circle that has been stretched in one direction, to
give it the shape of an oval.");
}

void calcArea(){
System.out.print("I will not calculate the area of ellipse. It needs extreme
hard work\n");
10
Gaurav 2820109

void getSides(){
System.out.print("No of sides in point is : infinite\n");
}
}

// TRIANGLE
class triangle extends Shape{

triangle(){
setShape("A triangle is a three-sided polygon, which has three vertices.
The three sides are connected with each other end to end at a point, which forms
the angles of the triangle. The sum of all three angles of the triangle is equal to
180 degrees.");
}

void calcArea(){
setSides(8, 5);
System.out.print("Area is: "+ 0.5*lengthOfSide1*lengthOfSide2);
}

void getSides(){
System.out.print("No of sides in point is : "+3+"\n");
}
}

// POLYGENETIC
class polygenetic extends Shape{

polygenetic(){
setShape("Polygenetic is similar to bell-shaped.");
}

void calcArea(){
System.out.print("Do you know what you are asking me to do?\n");
}
11
Gaurav 2820109

void getSides(){
System.out.print("No of sides in point is : infinite\n");
    }
}

Output: -

12
Gaurav 2820109

PROGRAM NO. - 4

13
Gaurav 2820109

Design a simple test application to demonstrate dynamic polymorphism.

import java.io.*;
import java.util.*;
class Lab4
{
public static void main(String args[])
{
System.out.println("\n\nGaurav -- 2820109\n");
//assigning a child class object to a parent class reference
Fruits fruits = new Mango();
//invoking the method
fruits.color();
}
}
//parent class
class Fruits
{
public void color()
{
System.out.println("Parent class method is invoked.");
}
}
//derived or child class that extends the parent class
class Mango extends Fruits
{
//overrides the color() method of the parent class
@Override
public void color()
{
System.out.println("The child class method is invoked.");
}
}
Output: -

14
Gaurav 2820109

PROGRAM NO. - 5

Design a java interface for ADT Stack.

import java.io.*;
15
Gaurav 2820109

interface StackOperation
{
public void push(int i);
public void pop();

public static void main(String args[])


{
System.out.println(“\n\nGaurav -- 2820109\n”);
StackDemo s=new StackDemo();
s.push(10);
s.pop();

class StackDemo implements StackOperation


{
int stack[]=new int[5];
int top=-1;
int i;

public void push(int item)


{
if(top>=4)
{
System.out.println("overflow");
}
else
{
top=top+1;
stack[top]=item;
System.out.println("item pushed "+stack[top]);
}
}

16
Gaurav 2820109

public void pop()


{
if(top<0)
System.out.println("underflow ");
else
{
System.out.println("item popped "+stack[top]);
top=top-1;
}
}

public void display()


{
if(top<0)
System.out.println("No Element in stack"); else
{
for(i=0;i<=top;i++)
System.out.println("element: "+stack[i]);
}
}
}

Output: -

17
Gaurav 2820109

PROGRAM NO. - 6

Develop two different classes that implement this interface. One using array and other
using linked list.

18
Gaurav 2820109

import java.io.*;
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);
19
Gaurav 2820109

        }
    }

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

20
Gaurav 2820109

    {
        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
        {

21
Gaurav 2820109

            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("Gaurav 2820109");

        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 4.Exit 5.Use Linked List");
            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;
                case 4:
                    System.exit(0);
            }
        }
        while(ch<5);

        System.out.println("Implementation of Stack using Linked List");


        Stack_List stk1=new Stack_List(); ch=0;
        do
        {

22
Gaurav 2820109

            System.out.println("1.Push 2.Pop3.Display 4.Exit");


            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;
                default:
                    System.exit(0);
            }
        }
        while(ch<5);
     }
}

23
Gaurav 2820109

Output: -

24
Gaurav 2820109

PROGRAM NO. - 7

Develop a simple paint like program that can draw basic graphical primitives.

25
Gaurav 2820109

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

/**
 * A simple applet where the user can sketch curves in a variety of
 * colors.  A color palette is shown along the right edge of the applet.
 * The user can select a drawing color by clicking on a color in the
 * palette.  Under the colors is a "Clear button" that the user
 * can press to clear the sketch.  The user draws by clicking and
 * dragging in a large white area that occupies most of the applet.
 * The user's drawing is not persistent.  It is lost whenever
 * the applet is repainted for any reason.
 * <p>The drawing that is done in this example violates the rule
 * that all drawing should be done in the paintComponent() method.
 * Although it works, it is NOT good style.
 * <p>This class also contains a main program, and it can be run as
 * a stand-alone application that has exactly the same functionality
 * as the applet.
 */
public class SimplePaint extends JApplet {
   
   /**
    * The main routine opens a window that displays a drawing area
    * and color palette.  This main routine allows this class to
    * be run as a stand-alone application as well as as an applet.
    * The main routine has nothing to do with the function of this
    * class as an applet.
    */
   public static void main(String[] args) {
      JFrame window = new JFrame("Simple Paint");
      SimplePaintPanel content = new SimplePaintPanel();
      window.setContentPane(content);
      window.setSize(600,480);
      window.setLocation(100,100);
      window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
      window.setVisible(true);

   }
   
   /**
    * The init method of the applet simply creates a SimplePaintPanel and
    * uses it as the content pane of the applet.  All the work is done
    * by the SimplePaintPanel.
26
Gaurav 2820109

    */
   public void init() {
      setContentPane( new SimplePaintPanel() );
   }
   
   
   /**
    * A simple paint panel contains a large white drawing surface where
    * the user can draw curves and a color palette that the user can click
    * to select the color to be used for drawing.  When this class is used
    * as an applet, the content pane of the applet is a SimplePaintPanel.
    * When this class is run as a standalone application, the content pane
    * is a SimplePaintPanel.  All the real work is done in the
    * SimplePaintPanel class.
    */
   public static class SimplePaintPanel extends JPanel
               implements MouseListener, MouseMotionListener {
     
      /**
       * Some constants to represent the color selected by the user.
       */
      private final static int BLACK = 0,
                        RED = 1,    
                        GREEN = 2,  
                        BLUE = 3,
                        CYAN = 4,  
                        MAGENTA = 5,
                        YELLOW = 6;
     
      private int currentColor = BLACK;  // The currently selected drawing color,
                                         //   coded as one of the above constants.
     
     
      /* The following variables are used when the user is sketching a
       curve while dragging a mouse. */
     
      private int prevX, prevY;     // The previous location of the mouse.
     
      private boolean dragging;      // This is set to true while the user is drawing.
     
      private Graphics graphicsForDrawing;  // A graphics context for the panel
                                  // that is used to draw the user's curve.
     
     
      /**
       * Constructor for SimplePaintPanel class sets the background color to be

27
Gaurav 2820109

       * white and sets it to listen for mouse events on itself.


       */
      SimplePaintPanel() {
         setBackground(Color.WHITE);
         addMouseListener(this);
         addMouseMotionListener(this);
      }
     
           
      /**
       * Draw the contents of the panel.  Since no information is
       * saved about what the user has drawn, the user's drawing
       * is erased whenever this routine is called.
       */
      public void paintComponent(Graphics g) {
         
         super.paintComponent(g);  // Fill with background color (white).
         
         int width = getWidth();    // Width of the panel.
         int height = getHeight();  // Height of the panel.
         
         int colorSpacing = (height - 56) / 7;
            // Distance between the top of one colored rectangle in the palette
            // and the top of the rectangle below it.  The height of the
            // rectangle will be colorSpacing - 3.  There are 7 colored rectangles,
            // so the available space is divided by 7.  The available space allows
            // for the gray border and the 50-by-50 CLEAR button.
               
         /* Draw a 3-pixel border around the applet in gray.  This has to be
          done by drawing three rectangles of different sizes. */
         
         g.setColor(Color.GRAY);
         g.drawRect(0, 0, width-1, height-1);
         g.drawRect(1, 1, width-3, height-3);
         g.drawRect(2, 2, width-5, height-5);
         
         /* Draw a 56-pixel wide gray rectangle along the right edge of the applet.
          The color palette and Clear button will be drawn on top of this.
          (This covers some of the same area as the border I just drew. */
         
         g.fillRect(width - 56, 0, 56, height);
         
         /* Draw the "Clear button" as a 50-by-50 white rectangle in the lower right
          corner of the applet, allowing for a 3-pixel border. */
         
         g.setColor(Color.WHITE);

28
Gaurav 2820109

         g.fillRect(width-53,  height-53, 50, 50);


         g.setColor(Color.BLACK);
         g.drawRect(width-53, height-53, 49, 49);
         g.drawString("CLEAR", width-48, height-23);
         
         /* Draw the seven color rectangles. */
         
         g.setColor(Color.BLACK);
         g.fillRect(width-53, 3 + 0*colorSpacing, 50, colorSpacing-3);
         g.setColor(Color.RED);
         g.fillRect(width-53, 3 + 1*colorSpacing, 50, colorSpacing-3);
         g.setColor(Color.GREEN);
         g.fillRect(width-53, 3 + 2*colorSpacing, 50, colorSpacing-3);
         g.setColor(Color.BLUE);
         g.fillRect(width-53, 3 + 3*colorSpacing, 50, colorSpacing-3);
         g.setColor(Color.CYAN);
         g.fillRect(width-53, 3 + 4*colorSpacing, 50, colorSpacing-3);
         g.setColor(Color.MAGENTA);
         g.fillRect(width-53, 3 + 5*colorSpacing, 50, colorSpacing-3);
         g.setColor(Color.YELLOW);
         g.fillRect(width-53, 3 + 6*colorSpacing, 50, colorSpacing-3);
         
         /* Draw a 2-pixel white border around the color rectangle
          of the current drawing color. */
         
         g.setColor(Color.WHITE);
         g.drawRect(width-55, 1 + currentColor*colorSpacing, 53, colorSpacing);
         g.drawRect(width-54, 2 + currentColor*colorSpacing, 51, colorSpacing-2);
         
      } // end paintComponent()
     
     
      /**
       * Change the drawing color after the user has clicked the
       * mouse on the color palette at a point with y-coordinate y.
       * (Note that I can't just call repaint and redraw the whole
       * panel, since that would erase the user's drawing!)
       */
      private void changeColor(int y) {
         
         int width = getWidth();           // Width of applet.
         int height = getHeight();         // Height of applet.
         int colorSpacing = (height - 56) / 7;  // Space for one color rectangle.
         int newColor = y / colorSpacing;       // Which color number was clicked?
         
         if (newColor < 0 || newColor > 6)      // Make sure the color number is valid.

29
Gaurav 2820109

            return;
         
         /* Remove the hilite from the current color, by drawing over it in gray.
          Then change the current drawing color and draw a hilite around the
          new drawing color.  */
         
         Graphics g = getGraphics();
         g.setColor(Color.GRAY);
         g.drawRect(width-55, 1 + currentColor*colorSpacing, 53, colorSpacing);
         g.drawRect(width-54, 2 + currentColor*colorSpacing, 51, colorSpacing-2);
         currentColor = newColor;
         g.setColor(Color.WHITE);
         g.drawRect(width-55, 1 + currentColor*colorSpacing, 53, colorSpacing);
         g.drawRect(width-54, 2 + currentColor*colorSpacing, 51, colorSpacing-2);
         g.dispose();
         
      } // end changeColor()
     
     
      /**
       * This routine is called in mousePressed when the user clicks on the drawing area.
         * It sets up the graphics context, graphicsForDrawing, to be used to draw the
user's
         * sketch in the current color.
       */
      private void setUpDrawingGraphics() {
         graphicsForDrawing = getGraphics();
         switch (currentColor) {
         case BLACK:
            graphicsForDrawing.setColor(Color.BLACK);
            break;
         case RED:
            graphicsForDrawing.setColor(Color.RED);
            break;
         case GREEN:
            graphicsForDrawing.setColor(Color.GREEN);
            break;
         case BLUE:
            graphicsForDrawing.setColor(Color.BLUE);
            break;
         case CYAN:
            graphicsForDrawing.setColor(Color.CYAN);
            break;
         case MAGENTA:
            graphicsForDrawing.setColor(Color.MAGENTA);
            break;

30
Gaurav 2820109

         case YELLOW:
            graphicsForDrawing.setColor(Color.YELLOW);
            break;
         }
      } // end setUpDrawingGraphics()
     
     
      /**
       * This is called when the user presses the mouse anywhere in the applet.  
       * There are three possible responses, depending on where the user clicked:  
       * Change the current color, clear the drawing, or start drawing a curve.  
       * (Or do nothing if user clicks on the border.)
       */
      public void mousePressed(MouseEvent evt) {
         
         int x = evt.getX();   // x-coordinate where the user clicked.
         int y = evt.getY();   // y-coordinate where the user clicked.
         
         int width = getWidth();    // Width of the panel.
         int height = getHeight();  // Height of the panel.
         
         if (dragging == true)  // Ignore mouse presses that occur
            return;            //    when user is already drawing a curve.
                                //    (This can happen if the user presses
                                //    two mouse buttons at the same time.)
         
         if (x > width - 53) {
               // User clicked to the right of the drawing area.
               // This click is either on the clear button or
               // on the color palette.
            if (y > height - 53)
               repaint();       //  Clicked on "CLEAR button".
            else
               changeColor(y);  // Clicked on the color palette.
         }
         else if (x > 3 && x < width - 56 && y > 3 && y < height - 3) {
               // The user has clicked on the white drawing area.
               // Start drawing a curve from the point (x,y).
            prevX = x;
            prevY = y;
            dragging = true;
            setUpDrawingGraphics();
         }
         
      } // end mousePressed()
     

31
Gaurav 2820109

     
      /**
       * Called whenever the user releases the mouse button. If the user was drawing
       * a curve, the curve is done, so we should set drawing to false and get rid of
       * the graphics context that we created to use during the drawing.
       */
      public void mouseReleased(MouseEvent evt) {
         if (dragging == false)
            return;  // Nothing to do because the user isn't drawing.
         dragging = false;
         graphicsForDrawing.dispose();
         graphicsForDrawing = null;
      }
     
     
      /**
       * Called whenever the user moves the mouse while a mouse button is held down.  
       * If the user is drawing, draw a line segment from the previous mouse location
       * to the current mouse location, and set up prevX and prevY for the next call.  
       * Note that in case the user drags outside of the drawing area, the values of
       * x and y are "clamped" to lie within this area.  This avoids drawing on the color
       * palette or clear button.
       */
      public void mouseDragged(MouseEvent evt) {
         
         if (dragging == false)
            return;  // Nothing to do because the user isn't drawing.
         
         int x = evt.getX();   // x-coordinate of mouse.
         int y = evt.getY();   // y-coordinate of mouse.
         
         if (x < 3)                          // Adjust the value of x,
            x = 3;                           //   to make sure it's in
         if (x > getWidth() - 57)       //   the drawing area.
            x = getWidth() - 57;
         
         if (y < 3)                          // Adjust the value of y,
            y = 3;                           //   to make sure it's in
         if (y > getHeight() - 4)       //   the drawing area.
            y = getHeight() - 4;
         
         graphicsForDrawing.drawLine(prevX, prevY, x, y);  // Draw the line.
         
         prevX = x;  // Get ready for the next line segment in the curve.
         prevY = y;
         

32
Gaurav 2820109

      } // end mouseDragged()
     
     
      public void mouseEntered(MouseEvent evt) { }   // Some empty routines.
      public void mouseExited(MouseEvent evt) { }    //    (Required by the MouseListener
      public void mouseClicked(MouseEvent evt) { }   //    and MouseMotionListener
      public void mouseMoved(MouseEvent evt) { }     //    interfaces).
     
     
   }  // End class SimplePaintPanel

} // end class SimplePaint

Output: -

33
Gaurav 2820109

PROGRAM NO. - 8
34
Gaurav 2820109

Develop a scientific calculator using event driven programming.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
 
class Calculator extends JFrame {
    private final Font BIGGER_FONT = new Font("monspaced",Font.PLAIN, 20);
    private JTextField textfield;
    private boolean number = true;
    private String equalOp = "=";
    private CalculatorOp op = new CalculatorOp();
   
    public Calculator() {
        textfield = new JTextField("", 12);
        textfield.setHorizontalAlignment(JTextField.RIGHT);
        textfield.setFont(BIGGER_FONT);
        ActionListener numberListener = new NumberListener();
        String buttonOrder = "1234567890 ";
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridLayout(4, 4, 4, 4));
        for (int i = 0; i < buttonOrder.length(); i++) {
            String key = buttonOrder.substring(i, i+1);
            if (key.equals(" ")) {
                buttonPanel.add(new JLabel(""));
            } else {
                JButton button = new JButton(key);
                button.addActionListener(numberListener);
                button.setFont(BIGGER_FONT);
                buttonPanel.add(button);
            }
        }
        ActionListener operatorListener = new OperatorListener();
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(4, 4, 4, 4));
        String[] opOrder = {"+", "-", "*", "/","=","C","sin","cos","log"};
        for (int i = 0; i < opOrder.length; i++) {
            JButton button = new JButton(opOrder[i]);
            button.addActionListener(operatorListener);
            button.setFont(BIGGER_FONT);
            panel.add(button);
        }
        JPanel pan = new JPanel();
35
Gaurav 2820109

        pan.setLayout(new BorderLayout(4, 4));


        pan.add(textfield, BorderLayout.NORTH );
        pan.add(buttonPanel , BorderLayout.CENTER);
        pan.add(panel , BorderLayout.EAST);
        this.setContentPane(pan);
        this.pack();
        this.setTitle("Calculator");
        this.setResizable(false);
    }
    private void action() {
        number = true;
        textfield.setText("");
        equalOp = "=";
        op.setTotal("");
    }
    class OperatorListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            String displayText = textfield.getText();
            if (e.getActionCommand().equals("sin"))
            {
                textfield.setText("" +
Math.sin(Double.valueOf(displayText).doubleValue()));
               
            }else
            if (e.getActionCommand().equals("cos"))
            {
                textfield.setText("" +
Math.cos(Double.valueOf(displayText).doubleValue()));
               
            }
            else
            if (e.getActionCommand().equals("log"))
            {
                textfield.setText("" +
Math.log(Double.valueOf(displayText).doubleValue()));
               
            }
            else if (e.getActionCommand().equals("C"))
            {
                textfield.setText("");
            }
 
            else
            {
                if (number)
                {

36
Gaurav 2820109

                   
                    action();
                    textfield.setText("");
                   
                }
                else
                {
                    number = true;
                    if (equalOp.equals("="))
                    {
                        op.setTotal(displayText);
                    }else
                    if (equalOp.equals("+"))
                    {
                        op.add(displayText);
                    }
                    else if (equalOp.equals("-"))
                    {
                        op.subtract(displayText);
                    }
                    else if (equalOp.equals("*"))
                    {
                        op.multiply(displayText);
                    }
                    else if (equalOp.equals("/"))
                    {
                        op.divide(displayText);
                    }
                   
                    textfield.setText("" + op.getTotalString());
                    equalOp = e.getActionCommand();
                }
            }
        }
    }
    class NumberListener implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            String digit = event.getActionCommand();
            if (number) {
                textfield.setText(digit);
                number = false;
            } else {
                textfield.setText(textfield.getText() + digit);
            }
        }
    }

37
Gaurav 2820109

    public class CalculatorOp {


        private int total;
        public CalculatorOp() {
            total = 0;
        }
        public String getTotalString() {
            return ""+total;
        }
        public void setTotal(String n) {
            total = convertToNumber(n);
        }
        public void add(String n) {
            total += convertToNumber(n);
        }
        public void subtract(String n) {
            total -= convertToNumber(n);
        }
        public void multiply(String n) {
            total *= convertToNumber(n);
        }
        public void divide(String n) {
            total /= convertToNumber(n);
        }
        private int convertToNumber(String n) {
            return Integer.parseInt(n);
        }
    }
}
class SwingCalculator {
    public static void main(String[] args) {
        JFrame frame = new Calculator();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

Output: -

38
Gaurav 2820109

39
Gaurav 2820109

PROGRAM NO. - 9

Develop a template for linked list class along with its members in Java.

class Node{
Node next;
int data;
Node(int data){
this.data = data;
next = null;
}
}

class LinkedList{
Node head;
public static LinkedList insert(LinkedList list, int data){
Node new_node = new Node(data);
new_node.next = null;
if(list.head == null){
list.head = new_node;
}
else{
Node last = list.head;
while(last.next != null){
last = last.next;
}
last.next = new_node;
}
return list;
}

public static void main(String args[]){


LinkedList list = new LinkedList();
list = insert(list,1);
list = insert(list,2);
list = insert(list,3);
list = insert(list,4);
list = insert(list,5);
list = insert(list,6);
list = insert(list,7);
list = insert(list,8);
printList(list);
}

public static void printList(LinkedList list){


System.out.println("Gaurav \n 2820109");
40
Gaurav 2820109

Node currNode = list.head;


while(currNode != null){
System.out.print(currNode.data);
System.out.print(" ");
currNode = currNode.next;
}
}
}

41
Gaurav 2820109

Output: -

PROGRAM NO. - 10

Write a program to insert and view data using Servlets.


Import java.io.IOException;
Import java.io.PrintWriter;
Import java.sql.*;
Import javax.servlet.ServletException;
Import javax.servlet.annotation.WebServlet;
Import javax.servlet.http.HttpServlet;
Import javax.servlet.http.HttpServletRequest;
Import javax.servlet.http.HttpServletResponse;

@WebServlet(“/MovieServlet”)
Public class MovieServlet extends HttpServlet

42
Gaurav 2820109

{ Private static final long serialVersionUID = 1L;


Public MovieServlet() { Super();
}
Protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
Response.getWriter().append(“Served at: “).append(request.getContextPath());
}
Protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
PrintWriter pw;
Response.setContentType(“text/html”);
Pw=response.getWriter();
String name=request.getParameter(“name”);
String actor=request.getParameter(“actor”);
String actress=request.getParameter(“actress”);
String director=request.getParameter(“director”);
String rDate=request.getParameter(“rDate”);
String rPoint=request.getParameter(“rPoint”); Float rating=Float.parseFloat(rPoint);
Try
{
Class.forName(“com.mysql.jdbc.Driver”);
String url=”jdbc:mysql:
//localhost:3306/bcapracticals”;
String user=”root”;
String password=”admin”;
Connection con=DriverManager.getConnection(url, user, password);
String query=”Insert into movie(name,actor,actress,director,releaseDate,ratingPoint) values (?,?,?,?,?,?);
PreparedStatement pstmt=con.prepareStatement(query);
Pstmt.setString(1, name);
mt.setString(2, actor);
Pstmt.setString(3,actress);
Pstmt.setString(4, director);
Pstmt.setString(5, rDate);
Pstmt.setFloat(6,rating);
Int x=pstmt.executeUpdate();
If(x==1){
Pw.println(“Values Inserted Successfully”);
}
}
Catch(Exception e) {
e.printStackTrace();
}
Pw.close();
}
HTML CODE
<html>
<head><meta charset=”ISO-8859-1”>
43
Gaurav 2820109

<title>Insert title here</title>


</head>
<body>
<form method=”Post” action=”/BCAPracticals/MovieServlet”>
<div>
<label>Enter Movie Name: </label>
<input type=”text” name=”name”>
</div>
<div>
<label>Enter Actor Name: </label>
<input type=”text” name=”actor”></div>
<div>
<label>Enter Actress Name: </label>
<input type=”text” name=”actress”>
</div>
<div>
<label>Enter Director Name: </label>
<input type=”text” name=”director”>
</div>
<div>
<label>Enter Release Date: </label>
<input type=”text” name=”rDate”>
</div>
<div><label>Enter Rating Point: </label>
<input type=”text” name=”rPoint”>
</div>
<div>
<input type=”submit” value=”Add movie”>
</div>
</form>
</body>
</html>

44
Gaurav 2820109

Output: -

45
Gaurav 2820109

46

You might also like