flipkart

Friday, 24 April 2015

II B.Tech II Cse Java Programming Lab Manuals

WEEK 1

1. Use Eclipse or Netbean platform and acquaint with the various menus. Create a test project, add a test class and run it. See how you can use auto suggestions, auto fill. Try code formatter and code refactoring like renaming variables, methods and classes. Try debug step by step with java program to find prime numbers between 1 to n.

class PrimeNumbers
{

public static void main(String[] jbrec)
{
try
{
System.out.println("***** PRIME NUMBERS *****");

Scanner objScanner = new Scanner(System.in);

System.out.print("\nEnter n Value:");
long n = objScanner.nextInt();

for (long i = 2; i <= n; i++)
{
boolean isprime = isNumPrime(i);
if (isprime)
{
System.out.print(i + " ");
}
}
}
 catch (Exception e)
{
e.printStackTrace();
}
}

public static boolean isNumPrime(long number)
{
boolean result = true;

for (long i = 2; i <= number / 2; i++)
{
if ((number % i) != 0)
{
result = true;
}
else
{
result = false;
break;
}
}

return result;
}
}

WEEK 2
1. Write a java program that prints all real and imaginary solutions to the quadratic equation ax2+bx+c=0. Read in a, b, c and use the quadratic formula
import java.io.*;
class Quadratic
{
            public static void main(String args[])throws IOException
            {
                        double x1,x2,disc,a,b,c;
                        InputStreamReader obj=new InputStreamReader(System.in);
                        BufferedReader br=new BufferedReader(obj);
                        System.out.println("enter a,b,c values");
                        a=Double.parseDouble(br.readLine());
                        b=Double.parseDouble(br.readLine());
                        c=Double.parseDouble(br.readLine());
                        disc=(b*b)-(4*a*c);
                        if(disc==0)
                        {
                                    System.out.println("roots are real and equal ");
                                    x1=x2=-b/(2*a);
                                    System.out.println("roots are "+x1+","+x2);
                        }
                        else if(disc>0)
                        {
                                    System.out.println("roots are real and unequal");
                                    x1=(-b+Math.sqrt(disc))/(2*a);
                                    x2=(-b+Math.sqrt(disc))/(2*a);
                                    System.out.println("roots are "+x1+","+x2);
                        }
                        else
                        {
                                    System.out.println("roots are imaginary");
                        }
            }
}

2. Write a Java program for sorting a given list of names in ascending order
public class Sorting
{
    String str=new String();
        String[] names=new String[] {"King","Raja","Suresh","Arun"};
       
        for(int i=0;i<names.length;i++)
           
        System.out.println("Names are"+names[i]);
        System.out.println("Sorting names are");
        for(int i=0;i<names.length;i++)
            for(int j=0;j<names.length;j++)
            {
                if(names[i].compareToIgnoreCase(names[j])<0)
                {
                str=names[i];
                names[i]=names[j];
                names[j]=str;
                }
            }
        for(int i=0;i<names.length;i++)
           
        System.out.println("Names are"+names[i]);

Output:

Java sorting Harish Ramesh Mahesh Rakesh

Sorted order is
Ramesh
Rakesh
Mahesh
Harish

Java sorting sai hari teja ravi sandeep
Sorted order is
teja
sandeep
sai
ravi
hari

3. Write a java program to accept a string from user and display number of vowels, consonants, digits and special characters present in each of the words of the given text.

import java.io.*;
public class classString
{
public static void main(String args[])
{
    String str="This is java9 com SEEerverces123";
     int ln=str.length();
     System.out.println("STring length is"+ln);
     int d=0,v=0,s=0,c=0;
     for(int i=0;i<ln;i++)
     {
         char ch=str.charAt(i);
        
         if(((ch>='a') && (ch<='z')) || ((ch>='A') && (ch<='Z')))
         {
  if(ch=='a'|| ch=='e'|| ch=='i' || ch=='o' || ch=='u' || ch=='A'|| ch=='E'|| ch=='I' || ch=='O' || ch=='U')
                v++;
     else
                c++;
         }
         else if(ch>='0' && ch<='9')
                d++;
           else
             s++;
        
        
      }
    
     System.out.println("Digits"+d);
     System.out.println("Vowels"+v);
     System.out.println("Consonents"+c);
     System.out.println("Special Characters"+s);
    
}
}

OUTPUT:

STring length is32
Digits4
Vowels10
Consonents14


Special Characters4

WEEK 3

1. Write a java program to make rolling a pair of dice 10,000 times and counts the number of times doubles of are rolled for each different pair of doubles.

Hint: Math.random()
import java.util.Random; // to use random number generator

/**
 * This program performs the following type of experiment:  Given a desired
 * total roll, such as 7, roll a pair of dice until the given total comes up,
 * and count how many rolls are necessary.  Now do that over and over, and
 * find the average number of rolls.  The number of times the experiment is
 * repeated is given by the constant, NUMBER_OF_EXPERIMENTS.  The average is
 * computed and printed out for each possible roll = 2, 3, ..., 12.
 */

public class Dice
{

   /**
    * The number of times that the experiment "roll for a given total"
    * is to be repeated.  The program performs this many experiments, and
    * prints the average of the result, for each possible roll value,
    */
   public static final int NUMBER_OF_EXPERIMENTS = 10000;

   public static void main(String[] args)
   {
       double average;  // The average number of rolls to get a given total.
       System.out.println("Total On Dice     Average Number of Rolls");
       System.out.println("-------------     -----------------------");
       for ( int dice = 2;  dice <= 12;  dice++ )
       {
          average = getAverageRollCount( dice );
          System.out.printf("%10d%22.4f\n", dice, average);
             // Use 10 spaces to output dice, and use 22 spaces to output
             // average, with 4 digits after the decimal.
       }
   }
  
   /**
    * Find the average number of times a pair of dice must be rolled to get
    * a given total.  The experiment of rolling for the given total is
    * repeated NUMBER_OF_EXPERIMENTS times and the average number of rolls
    * over all the experiments is computed.
    * Precondition:  The given total must be be between 2 and 12, inclusive.
    * @param roll the total that we want to get on the dice
    * @return the average number of rolls that it takes to get the specified
    *    total
    */
   public static double getAverageRollCount( int roll )
   {
       int rollCountThisExperiment;  // Number of rolls in one experiment.
       int rollTotal;  // Total number of rolls in all the experiments.
       double averageRollCount;  // Average number of rolls per experiment.
       rollTotal = 0;
       for ( int i = 0;  i < NUMBER_OF_EXPERIMENTS;  i++ )
       {
          rollCountThisExperiment = rollFor( roll );
          rollTotal += rollCountThisExperiment;
       }
       averageRollCount = ((double)rollTotal) / NUMBER_OF_EXPERIMENTS;
       return averageRollCount;
   }
  
   /**
    * Simulates rolling a pair of dice until a given total comes up.
    * Precondition:  The desired total is between 2 and 12, inclusive.
    * @param N the total that we want to get on the dice
    * @return the number of times the dice are rolled before the
    *    desired total occurs
    * @throws IllegalArgumentException if the parameter, N, is not a number
    *    that could possibly come up on a pair of dice
    */
   public static int rollFor( int N )
   {
       if ( N < 2 || N > 12 )
          throw new IllegalArgumentException("Impossible total for a pair of dice.");
       int die1, die2;  // Numbers between 1 and 6 representing the dice.
       int roll;        // Total showing on dice.
       int rollCt;      // Number of rolls made.
       rollCt = 0;
       do {
          die1 = (int)(Math.random()*6) + 1;
          die2 = (int)(Math.random()*6) + 1;
          roll = die1 + die2;
          rollCt++;
       } while ( roll != N );
       return rollCt;
   }
  
}  // end DiceRollStats


2. Write java program that inputs 5 numbers, each between 10 and 100 inclusive. As each number is read display it only if it‘s not a duplicate of any number already read display the complete set of unique values input after the user enters each new value.


import java.util.Scanner;

public class Duplicate
 {
   
            public static void main(String[] args)
             {
                                    int a[]={0,0,0,0,0},t,i,j,s=0,r=0;
                                    Scanner z=new Scanner(System.in);
                                    System.out.println("Enter 5 unique values between 10 & 100 ");
                                    for(j=0;j<5;j++)
                                    {  
                                                t=z.nextInt();
                                                if(t>=10&&t<=100)
                                                { 
                                                            for(i=0;i<r;i++)
                                                            {
                                                                        if(a[i]==t)
                                                                        {
                                                                                    s++;
                                                                        }
                                                            }
                                                if(s>0)
                                                {
                                                            System.out.println("Duplicate value found retry");
                                                                        s--;
                                                                        j--;
                                                                        continue;
                                                }
                                                else
                                                            {
                                                                        a[j]=t;
                                                                                    r++;
                                                            }
                                                }
                                                else
                                                {
                                                System.out.println("value must be in between 10 & 100");
                                                            j--;
                                                }   
                                    }
                                                 System.out.print("The five unique values are ");
                                    for(i=0;i<5;i++)
                                    {
                                                            System.out.print(a[i]+" ");
                                    }       
               
            }
   
}

Output:-
Enter 5 unique values between 10 & 100
0
value must be in between 10 & 100
10
20
10
Duplicate value found retry
30
40
50
The five unique values are 10 20 30 40 50




3. Write a java program to read the time intervals (HH:MM) and to compare system time if the system time between your time intervals print correct time and exit else try again to repute the same thing. By using StringToknizer class.


import java.util.*;
import java.text.*;
class Tokenizer
{
    static int[] cal(String y)
            {
                String a,b,x=":";
                int i[] = {0,0};
                StringTokenizer st=new StringTokenizer(y,x);
                a=(String) st.nextElement();
                b=(String) st.nextElement();
                i[0]=Integer.parseInt(a);
                i[1]=Integer.parseInt(b); 
                return i;
            }
}
  public class GetCurrentDateTime
{
  public static void main(String[] args) {

               DateFormat dateFormat = new SimpleDateFormat("HH:mm");
               Calendar cal = Calendar.getInstance();
           String y=dateFormat.format(cal.getTime());
             
           while(true)
            {
                       
                        String x,t1,a,b;int minute,hour;
                        int HH[]={0,0},MM[]={0,0};
                        t1=dateFormat.format(cal.getTime());
                int time1[]=Tokenizer.cal(t1);
                hour=time1[0];
                minute=time1[1];
                System.out.println("Enter the time intervels in HH MM fommat");
                        Scanner z=new Scanner(System.in);
                String t2=z.next();
                String t3=z.next();
                int time2[]=Tokenizer.cal(t2);
                        HH[0]=time2[0];
                        MM[0]=time2[1];
                int time3[]=Tokenizer.cal(t3);
                        HH[1]=time3[0];
                        MM[1]=time3[1];
                if(HH[0]>HH[1])
                {
                    int t=HH[0];
                    HH[0]=HH[1];
                    HH[1]=t;
                }
                if(HH[0]==HH[1]&&MM[0]>MM[1])
                {
                    int t=MM[0];
                    MM[0]=MM[1];
                    MM[1]=t;
                }
              
                if((hour>=HH[0]&&hour<HH[1])||(hour==HH[0]&&hour==HH[1])&&(minute>=MM[0]&&minute<=MM[1]))
                        {
                                    System.out.println("Current time is  "+hour+" : "+minute);
                                    break;
                        }
               else
                {
                    System.out.println("Try again");
                }

        }
  }
}
                               
Week-4

1.     Write a java program to split a given text file into n parts. Name each part as the name of the original file followed by .part<n> where n is the sequence number of the part file.

import java.io.*; 
import java.util.Scanner; 
public class Split { 
public static void main(String args[]) 
 try{ 
  // Reading file and getting no. of files to be generated 
  String inputfile = "D:\\test.txt"; //  Source File Name. 
  double nol = 2000.0; //  No. of lines to be split and saved in each output file. 
  File file = new File(inputfile); 
  Scanner scanner = new Scanner(file); 
  int count = 0; 
  while (scanner.hasNextLine())  
  { 
   scanner.nextLine(); 
   count++; 
  } 
  System.out.println("Lines in the file: " + count);     // Displays no. of lines in the input file. 

  double temp = (count/nol); 
  int temp1=(int)temp; 
  int nof=0; 
  if(temp1==temp) 
  { 
   nof=temp1; 
  } 
  else 
  { 
   nof=temp1+1; 
  } 
  System.out.println("No. of files to be generated :"+nof); // Displays no. of files to be generated. 

  //--------------------------------------------------------------------------------------------------------- 

  // Actual splitting of file into smaller files 

  FileInputStream fstream = new FileInputStream(inputfile); DataInputStream in = new DataInputStream(fstream); 

  BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; 

  for (int j=1;j<=nof;j++) 
  { 
   FileWriter fstream1 = new FileWriter("C:/New Folder/File"+j+".txt");     // Destination File Location 
   BufferedWriter out = new BufferedWriter(fstream1);  
   for (int i=1;i<=nol;i++) 
   { 
    strLine = br.readLine();  
    if (strLine!= null) 
    { 
     out.write(strLine);  
     if(i!=nol) 
     { 
      out.newLine(); 
     } 
    } 
   } 
   out.close(); 
  } 

  in.close(); 
 }catch (Exception e) 
 { 
  System.err.println("Error: " + e.getMessage()); 
 } 


}  

2. Write java program to create a super class called Figure that receives the dimensions of two dimensional objects. It also defines a method called area that computes the area of an object. The program derives two subclasses from Figure. The first is Rectangle and second is Triangle. Each of the sub class overridden area () so that it returns the area of a rectangle and a triangle respectively.

// Using abstract methods and classes. 
abstract class Figure { 
double dim1; 
double dim2; 
Figure(double a, double b) { 
dim1 = a; 
dim2 = b; 

// area is now an abstract method 
abstract double area(); 
}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref; // this is OK, no object is created
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
}
}


3. Write a Java program that creates three threads. First thread displays “Good Morning” every one second, the second thread displays “Hello” every two seconds and the third thread displays “Welcomeevery three seconds

class A extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(1000);
System.out.println("good morning");
}
}
catch(Exception e)
{                          }
}
}
class B extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(2000);
System.out.println("hello");
}
}
catch(Exception e)
{                          }
}
}
class C extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(3000);
System.out.println("welcome");
}
}
catch(Exception e)
{                         }
}
}
class ThreadDemo
{
public static void main(String args[])
{
A t1=new A();
B t2=new B();
C t3=new C();
t1.start();
t2.start();
t3.start();
}
}




Week-5

1. Write a Java program that correctly implements producer consumer problem using the concept of inter thread communication

class Q
{
               int n;
               boolean valueSet=false;
               synchronized int get()
               {
                               if(!valueSet)
                               try
                               {
                                              wait();
                               }
                               catch(InterruptedException e)
                               {
                                              System.out.println("Interrupted Exception caught");
                               }
                               System.out.println("Got:"+n);
                               valueSet=false;
                               notify();
                               return n;
               }
               synchronized void put(int n)
               {
                               if(valueSet)
                               try
                               {
                                              wait();
                               }
                               catch(InterruptedException e)
                               {
                                              System.out.println("Interrupted Exception caught");
                               }
                               this.n=n;
                               valueSet=true;
                               System.out.println("Put:"+n);
                               notify();
               }
}
class Producer implements Runnable
{
               Q q;
               Producer(Q q)
               {
                               this.q=q;
                               new Thread(this,"Producer").start();
               }
               public void run()
               {
                               int i=0;
                               while(true)
                               {
                                              q.put(i++);
                               }
               }
}
class Consumer implements Runnable
{
               Q q;
               Consumer(Q q)
               {
                               this.q=q;
                               new Thread(this,"Consumer").start();
               }
               public void run()
               {
                               while(true)
                               {
                                              q.get();
                               }
               }
}
class ProdCons
{
               public static void main(String[] args)
               {
                               Q q=new Q();
                               new Producer(q);
                              new Consumer(q);
                               System.out.println("Press Control-c to stop");
               }
}
Output:
Put:1
Got:1
Put:2
Got:2
Put:3
Got:3
Put:4
Got:4
Put:5
Got:5
Put:6
Got:6
Put:7
Got:7
Put:8
Got:8
Put:9
Got:9
Put:10
Got:10
Put:11
Got:11
Put:12
Got:12
Put:13
Got:13
Put:14
Got:14

2. Write a java program to find and replace pattern in given file.

import java.io.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

import java.io.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class PaternReplace
{
public static void main(String[] args) throws Exception
{
        FileInputStream fis=new FileInputStream("F:\\java\\test.txt");

        File file = new File("F:\\java\\test.txt");
                                    FileReader fileReader = new FileReader(file);
                                    BufferedReader bufferedReader = new BufferedReader(fileReader);
                                    StringBuffer source = new StringBuffer();
                                    String line;
                                    while ((line = bufferedReader.readLine()) != null) {
                                                source.append(line);
                                                source.append("\n");
                                    }
                                    fileReader.close();

                     
                     System.out.println(source);
              DataInputStream dis=new DataInputStream(System.in);
     




   
            FileOutputStream fos=new FileOutputStream("F:\\java\\test.txt");
   
 
   

            System.out.println("Enter to find word");

     
            String find=dis.readLine();

            System.out.println("Enter new word to replace");
            String replace=dis.readLine();

         

        Pattern pattern = Pattern.compile(find);

        Matcher matcher = pattern.matcher(source);

        String output = matcher.replaceAll(replace);

     
        byte[] b=output.getBytes();
        fos.write(b);


        System.out.println("Output = " + output);

    }
}



3. Use inheritance to create an exception super class called EexceptionA and exception sub class ExceptionB and ExceptionC, where ExceptionB inherits from ExceptionA and ExceptionC inherits from ExceptionB. Write a java program to demonstrate that the catch block for type ExceptionA catches exception of type ExceptionB and ExceptionC.

class ExceptionsA{
   static void genException(){
      int num[]= {4,8,16,32,64,128,256};
      int div[]= {2,0,4,4,0,8};
     
      for(int i=0; i<num.length; i++){
         System.out.println(num[i] + "/" +
               div[i] + "is" +
               num[i]/div[i]);
      }
   }
}  
class ExceptionsB extends ExceptionsA{
   ExceptionsB(){
      String zero;
      zero = ("Division by zero not allowed");
   }
}
class ExceptionsC extends ExceptionsB{
   ExceptionsC(){
      String array;
      array = ("Divisor element not found");
   }
}
class ExceptionTest{
   public static void main(String[] args){
      try {
         ExceptionsA.genException();
      }              
      catch (ArithmeticException zero){
         System.out.printf("%s",zero);
      }
      catch (ArrayIndexOutOfBoundsException array){
         System.out.printf("%s",array);
      }//end catch
   }//end class  
}//end method


Week-6

1. Write a java program to convert an ArrayList to an Array.

 
import java.util.*;

class ArrayListToArray

{

    public static void main(String args[])

    {

    ArrayList<String> a=new ArrayList<String>();



    a.add("Gowtham");

    a.add("Gutha's");

    a.add("Java");

    a.add("-");

    a.add("demos");

    a.add(".");

    a.add("blogspot");

    a.add(".");

    a.add("com");



    String st[]=a.toArray(new String[a.size()]);

    

    System.out.println("The elements are");



        for(String k:st)

        System.out.println(k);

    }

}






2. Write a Java Program for waving a Flag using Applets and Threads
//<applet code="Flag.class" height=300 width=300></applet>

//<applet code="Flag1.class" height=300 width=300></applet>
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Flag1 extends Applet implements ActionListener {
Button but = new Button ("click");
double add = 0;
public void init () {
setBackground (Color.white);
add (but);
but.addActionListener (this);
}
public void paint (Graphics g) {
Dimension d = getSize();
int height = d.height, width = d.width;
int x[ ] = new int[2*width], y[ ] = new int[2*width];
for (int color=0; color<3; color++) {
switch(color) {
case 0: g.setColor (Color.orange); break;
case 1: g.setColor (Color.white); break;
case 2: g.setColor (Color.green);
}
// The following 2 lines are actually one:
int size = fillArrays
(x, y, width/8, 3*width/4, (1+color)*height/5, height/5, 5, add);
g.fillPolygon (x, y, size);
}
}
// The following 2 lines are actually one:
int fillArrays
(int h[ ], int v[ ], int xStart, int wd, int yStart, int ht, int step, double extra) {
int count = 0;
// top line of the colour band:
for (int i=xStart; (i<=xStart+wd); i += step) {
h[count] = i;
v[count++] = yStart+(int)(ht*Math.sin(i/(0.2*wd)+extra));
}
int n = count -1;
// The values of the bottom line are not calculated.
// They're equal to to the values of the top line + ht
for (int i=h[count-1]; i>=xStart; i-=step) {
h[count] = i;
v[count++] = v[n--]+ht;
}
return count;
}
public void actionPerformed (ActionEvent evt) {
add += 0.7;
repaint();
}
}


3. Write a Java Program for Bouncing Ball (The ball while moving down has to increase the size and decrease the size while moving up)

import java.awt.*;
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
 
public class Ball extends JPanel implements Runnable {
 
    List<Ball> balls = new ArrayList<Ball>();   
Color color;
int diameter;
long delay;
private int x;
private int y;
private int vx;
private int vy;
 
public Ball(String ballcolor, int xvelocity, int yvelocity) {
    if(ballcolor == "red") {
        color = Color.red;
    }
    else if(ballcolor == "blue") {
        color = Color.blue;
    }
    else if(ballcolor == "black") {
        color = Color.black;
    }
    else if(ballcolor == "cyan") {
        color = Color.cyan;
    }
    else if(ballcolor == "darkGray") {
        color = Color.darkGray;
    }
    else if(ballcolor == "gray") {
        color = Color.gray;
    }
    else if(ballcolor == "green") {
        color = Color.green;
    }
    else if(ballcolor == "yellow") {
        color = Color.yellow;
    }
    else if(ballcolor == "lightGray") {
        color = Color.lightGray;
    }
    else if(ballcolor == "magenta") {
        color = Color.magenta;
    }
    else if(ballcolor == "orange") {
        color = Color.orange;
    }
    else if(ballcolor == "pink") {
        color = Color.pink;
    }
    else if(ballcolor == "white") {     
        color = Color.white;
    }
    diameter = 30;
    delay = 40;
    x = 1;
    y = 1;
    vx = xvelocity;
    vy = yvelocity;
}
 
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.setColor(color);
    g.fillOval(x,y,30,30); //adds color to circle
    g.setColor(Color.black);
    g2.drawOval(x,y,30,30); //draws circle
}
 
public void run() {
    while(isVisible()) {
        try {
            Thread.sleep(delay);
        } catch(InterruptedException e) {
            System.out.println("interrupted");
        }
        move();
        repaint();
    }
}
 
public void move() {
    if(x + vx < 0 || x + diameter + vx > getWidth()) {
        vx *= -1;
    }
    if(y + vy < 0 || y + diameter + vy > getHeight()) {
        vy *= -1;
    }
    x += vx;
    y += vy;
}
 
private void start() {
    while(!isVisible()) {
        try {
            Thread.sleep(25);
        } catch(InterruptedException e) {
            System.exit(1);
        }
    }
    Thread thread = new Thread(this);
    thread.setPriority(Thread.NORM_PRIORITY);
    thread.start();
}
 
public static void main(String[] args) {
    Ball ball1 = new Ball("red",3,2);
    Ball ball2 = new Ball("blue",6,2);
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(ball1);
    f.getContentPane().add(ball2);
    f.setSize(400,400);
    f.setLocation(200,200);
    f.setVisible(true);
    new Thread(ball1).start();
    new Thread(ball2).start();
}
}



Week-7
1. Write a Java Program for stack operation using Buttons and JOptionPane input and Message dialog box.

import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; public class VisStackApplet extends JApplet implements ActionListener, Runnable { ScrolledPanel visPanel; //Where to paint graphics MyScrollPane msp; Button executeButton; Button historyButton; TextArea userInputText; TextArea history; JFrame historyFrame; JTextField statusLine; MyStack theStack; // The data structure being demonstrated Font stackFont; int cellHeight = 20; // For drawing the stack. int cellWidth = 200; // How wide to plot pink rectangles int cellGap = 4; // vertical space between successive cells int topMargin = 25; // Space above top of stack. int fontSize = 16; // Height of font for displaying stack elemens. int leftMargin = 20; // x value for left side of cells int bottomMargin = 10; // Minimum space betw. bot. of visPanel and bot. of lowest cell. int leftOffset = 5; // space between left side of cell and contents string. int delay = 300; // default is to wait 300 ms between updates. Thread displayThread = null; public void init() { setSize(300,300); // default size of applet. visPanel = new ScrolledPanel(); visPanel.setPreferredSize(new Dimension(400,400)); msp = new MyScrollPane(visPanel); msp.setPreferredSize(new Dimension(400,200)); Container c = getContentPane(); c.setLayout(new BorderLayout()); c.add(msp, BorderLayout.CENTER); JPanel buttons = new JPanel(); buttons.setLayout(new FlowLayout()); JPanel controls = new JPanel(); controls.setLayout(new BorderLayout()); executeButton = new Button("Execute"); executeButton.addActionListener(this); buttons.add(executeButton); historyButton = new Button("History"); historyButton.addActionListener(this); buttons.add(historyButton); userInputText = new TextArea(";Enter commands here."); statusLine = new JTextField(); statusLine.setBackground(Color.lightGray); controls.add(buttons, BorderLayout.WEST); controls.add(userInputText, BorderLayout.CENTER); controls.add(statusLine, BorderLayout.SOUTH); controls.setPreferredSize(new Dimension(400,100)); c.add(controls, BorderLayout.SOUTH); c.validate(); theStack = new MyStack(); stackFont = new Font("Helvetica", Font.PLAIN, 20); history = new TextArea("VisStackApplet history:\n", 20, 40); } class ScrolledPanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); paintStack(g); } } class MyScrollPane extends JScrollPane { MyScrollPane(JPanel p) { super(p, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); } } class MyStack extends Vector { int n; // number of elements in the stack int npushes; // number of PUSH operations so far. int npops; // number of POP operations so far. void init() { n = 0; npushes = 0; npops = 0; } void push(Object elt) { add(n, elt); n++; npushes++; } Object pop() { if (n == 0) { return null; } Object o = lastElement(); n--; npops++; remove(n); return o; } } public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Execute")) { displayThread = new Thread(this); displayThread.start(); return; } if (e.getActionCommand().equals("History")) { if (historyFrame == null) { historyFrame = new JFrame("History of the VisStackApplet"); historyFrame.getContentPane().add(history); historyFrame.setSize(new Dimension(300,300)); } historyFrame.show(); System.out.println("Should have displayed the history window"); } } // The following is executed by a separate thread for the display. public void run() { String commands = userInputText.getText(); String line = ""; StringTokenizer lines; for (lines = new StringTokenizer(commands, "\n\r\f"); lines.hasMoreTokens();) { line = lines.nextToken(); process(line); } userInputText.setText(""); // Erase all the processed input. } // Helper function called by the run method above: void process(String command) { String arg = ""; StringTokenizer st = new StringTokenizer(command); if (! st.hasMoreTokens()) { return; } String firstToken = st.nextToken(); if (firstToken.startsWith(";")) { return; } history.appendText(command + "\n"); statusLine.setText(command); if (firstToken.equals("RESET")) { theStack = new MyStack(); updateDisplay(); return; } if (firstToken.equals("SIZE")) { String stats = "Current number of elements: " + theStack.n; statusLine.setText(stats); history.appendText("; " + stats + "\n"); return; } if (firstToken.equals("STATS")) { String stats = "npushes: " + theStack.npushes + "; npops: " + theStack.npops; statusLine.setText(stats); history.appendText("; " + stats + "\n"); return; } if (firstToken.equals("DELAY")) { if (st.hasMoreTokens()) { arg = st.nextToken(); try { delay =(new Integer(arg)).intValue(); } catch(NumberFormatException e) { delay = 0; } statusLine.setText("delay = " + delay); } history.appendText("; delay is now " + delay + "\n"); return; } if (firstToken.equals("PUSH")) { arg = "UNDEFINED ELEMENT"; if (st.hasMoreTokens()) { arg = st.nextToken(); } theStack.push(arg); checkScrolledPanelSize(); updateDisplay(); return; } if (firstToken.equals("POP")) { theStack.pop(); updateDisplay(); return; } history.appendText("[Unknown Stack command]\n"); statusLine.setText("Unknown Stack command: " + command); } // Here is a "middleman" method that updates the display waiting with // the current time delay after each repaint request. void updateDisplay() { visPanel.repaint(); if (delay > 0) { try { Thread.sleep(delay); } catch(InterruptedException e) {} } } // Here is the graphics method to actually draw the stack. // It's called by the ScrolledPanel paintComponent method. void paintStack(Graphics g) { g.setFont(stackFont); g.drawString( "Top of Stack", 10,20); int ystart = theStack.n * (cellHeight + cellGap) + topMargin; int ycentering = (cellHeight - fontSize) / 2; int ypos = ystart; for (Enumeration e = theStack.elements(); e.hasMoreElements();) { String elt = (String) e.nextElement(); g.setColor(Color.pink); g.fillRect(leftMargin, ypos, cellWidth, cellHeight); g.setColor(Color.black); g.drawString(elt, leftMargin + leftOffset, ypos+cellHeight - ycentering); ypos -= (cellHeight + cellGap); } } // The following computes the height of the display area needed by the current // stack, and if it won't fit in the scrolled panel, it enlarges the scrolled panel. // In the current implementation, the panel never gets smaller, even if the stack // becomes empty. This could easily be changed. void checkScrolledPanelSize() { int heightNeeded = topMargin + theStack.n * (cellHeight + cellGap) + cellHeight+ bottomMargin; Dimension d = visPanel.getPreferredSize(); int currentHeight = (int) d.getHeight(); int currentWidth = (int) d.getWidth(); if (heightNeeded > currentHeight) { visPanel.setPreferredSize(new Dimension(currentWidth, heightNeeded)); visPanel.revalidate(); // Adjust the vertical scroll bar. } } }
1.     Write a Java Program to Addition, Division, Multiplication and subtraction using JOptionPane dialog Box and Textfields.
import java.util.*; import javax.swing.*; public class Calculator { public static void main(String[] arg) { String input1,input2,operator; Double operand1,operand2; input1 = JOptionPane.showInputDialog("Enter 1st Value"); operator = JOptionPane.showInputDialog("Enter Operator(+,-,*,%./)"); input2 = JOptionPane.showInputDialog("Enter 2nd Value"); operand1=Double.parseDouble(input1); operand2=Double.parseDouble(input2); double result=0.0; if (operator.equals("+")) result = operand1+operand2; else if(operator.equals("-")) result = operand1-operand2; else if(operator.equals("*")) result = operand1*operand2; else if(operator.equals("/")) result = operand1/operand2; else if(operator.equals("%")) result = operand1%operand2; else JOptionPane.showMessageDialog(null, "Inappropriate Input"); JOptionPane.showMessageDialog(null,"Your results are " + result); } // TODO Auto-generated method stub private static double operand2(double result) { // TODO Auto-generated method stub return 0; } }
Week-8
1. Write a Java Program for the blinking eyes and mouth should open while blinking.
import java.applet.Applet; //<applet code="A.class" width=200 height=200></applet> import java.awt.BorderLayout; import java.awt.Canvas; import java.awt.Color; import java.awt.Graphics; public class A extends Applet { private static final long serialVersionUID = -1152278362796573663L; public class MyCanvas extends Canvas { private static final long serialVersionUID = -4372759074220420333L; private int flag = 0; public void paint(Graphics g) { draw(); } public void draw() { Graphics g = this.getGraphics(); g.setColor(Color.BLACK); super.paint(g); if (flag == 0) { System.out.println(flag); g.drawOval(40, 40, 120, 150);// face g.drawRect(57, 75, 30, 5);// left eye shut g.drawRect(110, 75, 30, 20);// right eye g.drawOval(85, 100, 30, 30);// nose g.fillArc(60, 125, 80, 40, 180, 180);// mouth g.drawOval(25, 92, 15, 30);// left ear g.drawOval(160, 92, 15, 30);// right ear flag = 1; } else { System.out.println(flag); g.drawOval(40, 40, 120, 150);// face g.drawOval(57, 75, 30, 20);// left eye g.drawOval(110, 75, 30, 20);// right eye g.fillOval(68, 81, 10, 10);// left pupil g.fillOval(121, 81, 10, 10);// right pupil g.drawOval(85, 100, 30, 30);// nose g.fillArc(60, 125, 80, 40, 180, 180);// mouth g.drawOval(25, 92, 15, 30);// left ear g.drawOval(160, 92, 15, 30);// right ear flag = 0; } try { Thread.sleep(900); } catch (Exception e) { System.out.println("killed while sleeping"); } this.repaint(100); } } public void init() { this.C = new MyCanvas(); this.setLayout(new BorderLayout()); this.add(C, BorderLayout.CENTER); C.setBackground(Color.GRAY); } private MyCanvas C; }
2. Implement a Java Program to add a new ball each time the user clicks the mouse. Provided a maximum of 20 balls randomly choose a color for each ball.
// <applet code="Ball.class" height=300 width=300></applet>
// Ball.java
// Program bounces a ball around the applet
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Ball extends JApplet
          implements Runnable, MouseListener {
   private Thread blueBall;
   private boolean xUp, yUp, bouncing;
   private int x, y, xDx, yDy;
   public void init()
   {
      xUp = false;
      yUp = false;
      xDx = 1;
      yDy = 1;
      addMouseListener( this );
      bouncing = false;
   }
   public void mousePressed( MouseEvent e )
   {
      if ( blueBall == null ) {
         x = e.getX();
         y = e.getY();
         blueBall = new Thread( this );
         bouncing = true;
         blueBall.start();
      }
   }
   public void stop()
   {
      if ( blueBall != null ) {
         blueBall = null;
      }
   }
   public void paint( Graphics g )
   {
      if ( bouncing ) {
         g.setColor( Color.blue );
         g.fillOval( x, y, 10, 10 );
      }
   }
   public void run()
   {
      while ( true ) {
         try {
            blueBall.sleep( 100 );
         }
         catch ( Exception e ) {
            System.err.println( "Exception: " + e.toString() );
         }
         if ( xUp == true )
            x += xDx;
         else
            x -= xDx;
         if ( yUp == true )
            y += yDy;
         else
            y -= yDy;
         if ( y <= 0 ) {
            yUp = true;           
            yDy = ( int ) ( Math.random() * 5 + 2 );
         }
         else if ( y >= 190 ) {
            yDy = ( int ) ( Math.random() * 5 + 2 );
            yUp = false;
         }
         if ( x <= 0 ) {
            xUp = true;
            xDx = ( int ) ( Math.random() * 5 + 2 );
         }
         else if ( x >= 190 ) {
            xUp = false;
            xDx = ( int ) ( Math.random() * 5 + 2 );
         }
         repaint();
      }
   }
   public void mouseExited( MouseEvent e ) {}
   public void mouseClicked( MouseEvent e ) {}
   public void mouseReleased( MouseEvent e ) {}
   public void mouseEntered( MouseEvent e ) {}    
}
Week-9
1. Suppose that a table named Table.txt is stored in a text file. The first line in the file is the header, and the remaining lines correspond to rows in the table. The elements are separated by commas. Write a java program to display the table using Jtable component
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class DataFileTableModel extends AbstractTableModel {
   
    protected Vector data;
    protected Vector columnNames ;
    protected String datafile;
   
    public DataFileTableModel(String f){
        datafile = f;
        initVectors();
    }
   
    public void initVectors() {
       
        String aLine ;
        data = new Vector();
        columnNames = new Vector();
       
        try {
            FileInputStream fin =  new FileInputStream(datafile);
            BufferedReader br = new BufferedReader(new InputStreamReader(fin));
            // extract column names
            StringTokenizer st1 =
                    new StringTokenizer(br.readLine(), ",");
            while(st1.hasMoreTokens())
                columnNames.addElement(st1.nextToken());
            // extract data
            while ((aLine = br.readLine()) != null) {
                StringTokenizer st2 =
                        new StringTokenizer(aLine, ",");
                while(st2.hasMoreTokens())
                    data.addElement(st2.nextToken());
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
   
    public int getRowCount() {
        return data.size() / getColumnCount();
    }
   
    public int getColumnCount(){
        return columnNames.size();
    }
   
    public String getColumnName(int columnIndex) {
        String colName = "";
       
        if (columnIndex <= getColumnCount())
            colName = (String)columnNames.elementAt(columnIndex);
       
        return colName;
    }
   
    public Class getColumnClass(int columnIndex){
        return String.class;
    }
   
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return false;
    }
   
    public Object getValueAt(int rowIndex, int columnIndex) {
        return (String)data.elementAt( (rowIndex * getColumnCount()) + columnIndex);
    }
   
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        return;
    }
}
public class DataFileTable extends JPanel {
    public DataFileTable(String dataFilePath) {
        JTable table;
        DataFileTableModel model;
        Font f;
       
        f = new Font("SanSerif",Font.PLAIN,24);
        setFont(f);
        setLayout(new BorderLayout());
       
        model = new DataFileTableModel(dataFilePath);
       
        table = new JTable();
        table.setModel(model);
        table.createDefaultColumnsFromModel();
       
        JScrollPane scrollpane = new JScrollPane(table);
        add(scrollpane);
    }
   
    public Dimension getPreferredSize(){
        return new Dimension(400, 300);
    }
   
    public static void main(String s[]) {
        JFrame frame = new JFrame("Data File Table");
        DataFileTable panel;
       
        panel = new DataFileTable("table.txt");
       
        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        frame.setForeground(Color.black);
        frame.setBackground(Color.lightGray);
        frame.getContentPane().add(panel,"Center");
       
        frame.setSize(panel.getPreferredSize());
        frame.setVisible(true);
        frame.addWindowListener(new WindowCloser());
    }
}
class WindowCloser extends WindowAdapter {
    public void windowClosing(WindowEvent e) {
        Window win = e.getWindow();
        win.setVisible(false);
        System.exit(0);
    }
}
Input
table.txt
Id,Name,City,Phone
101,Beth Reiser,New York,(212)5558725
111,Dylan Ricci,Syracuse,(315)5554486
116,Brian Gugliuzza,Mamaroneck,(914)5553817
120,Gertrude Stein,Elmsford,(914)5553476
131,Daljit Sinnot,Bohemia,(516)5559811
2. Write a program that creates a user interface to perform integer divisions. The user enters two numbers in the text fields, Num1 and Num2. The division of Num1 and Num2 is displayed in the Result field when the Divide button is clicked. If Num1 or Num2 were not an integer, the program would throw a NumberFormatException. If Num2 were Zero, the program would throw an ArithmeticException Display the exception in a message dialog box.
import java.awt.*; import java.awt.event.*; import java.applet.*; /*<applet code="Div"width=230 height=250> </applet>*/ public class Div extends Applet implements ActionListener { String msg; TextField num1,num2,res;Label l1,l2,l3; Button div; public void init() { l1=new Label("Number 1"); l2=new Label("Number 2"); l3=new Label("result"); num1=new TextField(10); num2=new TextField(10); res=new TextField(10); div=new Button("DIV"); div.addActionListener(this); add(l1); add(num1); add(l2); add(num2); add(l3); add(res); add(div); } public void actionPerformed(ActionEvent ae) { String arg=ae.getActionCommand(); if(arg.equals("DIV")) { String s1=num1.getText(); String s2=num2.getText(); int num1=Integer.parseInt(s1); int num2=Integer.parseInt(s2); if(num2==0) { try { System.out.println(" "); } catch(Exception e) { System.out.println("ArithematicException"+e); } msg="Arithemetic"; repaint(); } else if((num1<0)||(num2<0)) { try { System.out.println(""); } catch(Exception e) { System.out.println("NumberFormat"+e); } msg="NumberFormat"; repaint(); } else { int num3=num1/num2; res.setText(String.valueOf(num3)); } } } public void paint(Graphics g) { g.drawString(msg,30,70); } }
Add this images to the files




Week-10
1. Write a Java Program to implement the opening of a door while opening man should present before hut and closing man should disappear.
import javax.swing.*; import java.awt.*; import java.awt.event.*; class Animation extends JFrame implements ActionListener { ImageIcon ii1, ii2; Container c; JButton b1,b2; JLabel lb1; Animation() { c = getContentPane(); c.setLayout(null); ii1 = new ImageIcon("house0.jpg"); ii2 = new ImageIcon("house1.jpg"); lb1 = new JLabel(ii1); lb1.setBounds(50,10,500,500); b1 = new JButton("Open"); b2 = new JButton("Close"); b1.addActionListener(this); b2.addActionListener(this); b1.setBounds(650,240,70,40); b2.setBounds(650,320,70,40); c.add(lb1); c.add(b1); c.add(b2); } public void actionPerformed(ActionEvent ae) { String str = ae.getActionCommand(); if( str.equals("Open") ) lb1.setIcon(ii2); else lb1.setIcon(ii1); } public static void main(String args[]) { Animation ob = new Animation(); ob.setTitle("Animation"); ob.setSize(800,600); ob.setVisible(true); ob.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }

2. Write a Java code by using JtextField to read decimal value and converting a decimal number into binary number then print the binary value in another JtextField
// <applet code="Rottenapplet.class" height=300 width=300></applet>

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
public class rottenapplet extends JApplet implements ActionListener
{
JPanel mainpanel=new JPanel(new GridLayout (3,1));
JPanel p1=new JPanel(new FlowLayout(0));
JPanel p2=new JPanel(new FlowLayout (0));
JPanel p3=new JPanel(new FlowLayout ());
JTextField q1=new JTextField (10);
JTextField q2=new JTextField (10);
JButton clickbutton = new JButton("convert");
public void init()
{
getContentPane().add(mainpanel);
mainpanel.add(p1);
mainpanel.add(p2);
mainpanel.add(p3);
p1.add(new JLabel("Insert Decimal:"));
p1.add(q1);
p2.add(clickbutton);
p3.add(new JLabel("Decimal to Binary:"));
p3.add(q2);
clickbutton.addActionListener(this);
}
public void actionPerformed(ActionEvent x)
{
if(x.getSource()==clickbutton)
{
int counter,dec,user;
user=Integer.valueOf(q1.getText()).intValue();
String[]conversion=new String[8];
String[]complete=new String[4];
counter=0;
complete[0]="";
do
{
dec=user%2;
conversion[counter]=String.valueOf(dec);
complete[0]=conversion[counter]+complete[0];
user=user/2;
counter+=1;
}
while(user !=0);
q2.setText(String.valueOf(complete[user]));
}
}
}
Week-11
1. Write a Java program that works as a simple calculator. Use a grid layout to arrange buttons for the digits and for the +, -,*, % operations. Add a text field to display the result.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Cal" width=300 height=300>
</applet>
*/
public class Cal extends Applet
implements ActionListener
{
            String msg=" ";
            int v1,v2,result;
            TextField t1;
            Button b[]=new Button[10];
            Button add,sub,mul,div,clear,mod,EQ;
            char OP;
            public void init()
            {
                        Color k=new Color(120,89,90);
                        setBackground(k);
                        t1=new TextField(10);
                        GridLayout gl=new GridLayout(4,5);
                        setLayout(gl);
                        for(int i=0;i<10;i++)
                        {
                                    b[i]=new Button(""+i);
                        }
                        add=new Button("add");
                        sub=new Button("sub");
                        mul=new Button("mul");
                        div=new Button("div");
                        mod=new Button("mod");
                        clear=new Button("clear");
                        EQ=new Button("EQ");
                        t1.addActionListener(this);
                        add(t1);
                        for(int i=0;i<10;i++)
                        {
                                    add(b[i]);
                        }
                        add(add);
                        add(sub);
                        add(mul);
                        add(div);
                        add(mod);
                        add(clear);
                        add(EQ);
                        for(int i=0;i<10;i++)
                        {
                                    b[i].addActionListener(this);
                        }
                        add.addActionListener(this);
                        sub.addActionListener(this);
                        mul.addActionListener(this);
                        div.addActionListener(this);
                        mod.addActionListener(this);
                        clear.addActionListener(this);
                        EQ.addActionListener(this);
            }
            public void actionPerformed(ActionEvent ae)
            {
                        String str=ae.getActionCommand();
                        char ch=str.charAt(0);
                        if ( Character.isDigit(ch))
                        t1.setText(t1.getText()+str);
                        else
                        if(str.equals("add"))
                        {
                                    v1=Integer.parseInt(t1.getText());
                                    OP='+';
                                    t1.setText("");
                        }
                        else if(str.equals("sub"))
                        {
                                    v1=Integer.parseInt(t1.getText());
                                    OP='-';
                                    t1.setText("");
                        }
                        else if(str.equals("mul"))
                        {
                                    v1=Integer.parseInt(t1.getText());
                                    OP='*';
                                    t1.setText("");
                        }
                        else if(str.equals("div"))
                        {
                                    v1=Integer.parseInt(t1.getText());
                                    OP='/';
                                    t1.setText("");
                        }
                        else if(str.equals("mod"))
                        {
                                    v1=Integer.parseInt(t1.getText());
                                    OP='%';
                                    t1.setText("");
                        }
                        if(str.equals("EQ"))
                        {
                                    v2=Integer.parseInt(t1.getText());
                                    if(OP=='+')
                                                result=v1+v2;
                                    else if(OP=='-')
                                                result=v1-v2;
                                    else if(OP=='*')
                                                result=v1*v2;
                                    else if(OP=='/')
                                                result=v1/v2;
                                    else if(OP=='%')
                                                result=v1%v2;
                                    t1.setText(""+result);
                        }          
                        if(str.equals("clear"))
                        {
                                    t1.setText("");
                        }
            }
}
Output:
2. Write a Java program for handling mouse events.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Mouse" width=500 height=500>
</applet>
*/
public class Mouse extends Applet
implements MouseListener,MouseMotionListener
{
            int X=0,Y=20;
            String msg="MouseEvents";
            public void init()
            {
                        addMouseListener(this);
                        addMouseMotionListener(this);
                        setBackground(Color.black);
                        setForeground(Color.red);
            }
            public void mouseEntered(MouseEvent m)
            {
                        setBackground(Color.magenta);
                        showStatus("Mouse Entered");
                        repaint();
            }
            public void mouseExited(MouseEvent m)
            {
                        setBackground(Color.black);
                        showStatus("Mouse Exited");
                        repaint();
            }
            public void mousePressed(MouseEvent m)
            {
                        X=10;
                        Y=20;
                        msg="NEC";
                        setBackground(Color.green);
                        repaint();
            }
            public void mouseReleased(MouseEvent m)
            {
                        X=10;
                        Y=20;
                        msg="Engineering";
                        setBackground(Color.blue);
                        repaint();
            }
            public void mouseMoved(MouseEvent m)
            {
                        X=m.getX();
                        Y=m.getY();
                        msg="College";
                        setBackground(Color.white);
                        showStatus("Mouse Moved");
                        repaint();
            }
            public void mouseDragged(MouseEvent m)
            {
                        msg="CSE";
                        setBackground(Color.yellow);
                        showStatus("Mouse Moved"+m.getX()+" "+m.getY());
                        repaint();
            }
            public void mouseClicked(MouseEvent m)
            {
                        msg="Students";
                        setBackground(Color.pink);
                        showStatus("Mouse Clicked");
                        repaint();
            }
            public void paint(Graphics g)
            {
                        g.drawString(msg,X,Y);
            }
}
Week-12
1. Write a java program establishes a JDBC connection, create a table student with properties name, register number, mark1, mark2, mark3. Insert the values into the table by using the java and display the information of the students at front end.
Import java.awt.*;
Import javax.swing.*;
Import java.sql.*;
Class StudentForm extends JFrame
{
JLable l1,l2,l3,l4,l5,l6,l7;
JTextField t1,t2,t3,t4,t5,t6,t7;
JButton b1,b2;
Connection con;
PreparedStatement insert;
PreparedStatement update;
PreparedStatement delet;
PreparedStatement select;
StudentForm()
{
setSize(355,300);
setLocation(100,100);
Container c=getContentPane();
Title=new JLabel(“Student Details”);
Title.setFont(new Font(“Dialog”,Font.BOLD,15));
l1=new JLable(“Register No”);
l2=new JLable(“Student Name”);
l3=new JLable(“Marks1”);
l4=new JLable(“Marks2”);
l5=new JLable(“Marks3”);
t1=new JTextField(10);
t2=new JTextField(10);
t3=new JTextField(10);
t4=new JTextField(10);
t5=new JTextField(10);
b1=new JButton(“Insert”);
b2=new JButton(“Display”);
c.setLayout(null);
title.setBounds(60,10,160,20);
c.add(title);
l1.setBounds(40,40,50,20);
c.add(l1);
t1.setBounds(95,40,108,20);
c.add(t1);
l2.setBounds(40,70,50,20);
c.add(l2);
t2.setBounds(95,70,108,20);
c.add(t2);
l3.setBounds(40,100,50,20);
c.add(l3);
t3.setBounds(95,100,108,20);
c.add(t3);
b1.setBounds(10,140,65,40);
c.add(b1);
b2.setBounds(77,140,65,40);
c.add(b2);
//b3.setBounds(144,140,65,40);
//c.add(b3);
//b4.setBounds(211,140,65,40);
//c.add(b4);
Info=new Label(“Getting connected to the database”);
Info.setFont(new Font(“Dialog”,Font.BOLD,15));
Info.setBounds(20,190,330,30);
c.add(info);
b1.addActionListener(new InsertListener());
b2.addActionListener(new DisplayListener());
setVisible(true);
getConnection();
}
Void getConnection()
{
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
String url=”jdbc:odbc:student”;
Con=DriverManager.getConnection(url,”scott”,”tiger”);
Info.setText(“Connection is established with the database”);
insertps=con.prepareStatement(“Insert into student values(?,?,?,?,?)”);
selectps=con.prepareStatement(“select * from student where studentno=?”);
}
Catch(ClassNotFoundExceptoin e)
{
System.out.println(“Driver class not found….”);
System.out.println(e);
}
Catch(SQLExceptoin e)
{
Info.setText(“Unable to get connected to the database”);
}
}
Class insertListener implements ActionListener
{
Public void actionPerformed(ActionEvent e)
{
Try
{
Int sno=Integer.parseInt(t1.getText());
String name=t2.getText();
Int m1= Integer.parseInt(t3.getText());
Int m2=Integer.parseInt(t1.getText());
Int m3=Integer.parseInt(t1.getText());
Insertps.setInt(1,sno);
Insertps.setString(2,name);
Insertps.setInt(3,m1);
Insertps.setInt(4,m2);
Insertps.setInt(5,m3);
Insertps.executeUpdate();
Info.setText(“One row inserted successfully”);
Insertps.clearParameters();
T1.setText(“”);
T2.setText(“”);
T3.setText(“”);
T4.setText(“”);
T5.setText(“”);
}
Catch(SQLException se)
{
Info.setText(“Failed to insert a record…”);
}
Catch(Exception de)
{
Info.setText(“enter proper data before insertion….”);
}
}
}
Class DisplayListener implements ActionListener
{
Public void actionPerformed(ActionEvent e)
{
            Try
            {
                        Int sno=Integer.parseInt(t1.getText());
                        Selectps.setInt(1,sno);
                        Selectps.execute();
                        ResultSet rs=selectps.getResultSet();
                        rs.next();
                        t2.setText(rs.getString(2));
                        t3.setText(“”+rs.getFloat(3));
                        info.setText(“One row displayed successfully”);
                        selectps.clearPameters();
            }
            Catch(SQLException se)
            {
            Info.setText(“Failed to show the record…”);
            }
            Catch(Exception de)
{
Info.setText(“enter proper student no before selecting show..”);
}
}
}
Public static void main(String args[])
{
New StudentForm();
}
}

1 comment:

  1. Bro this is great bro i am searching for codes one by one but you made it simple for all the CSE students. Behalf off SVIT(Sri venkateswara institute of technology) ananthapur CSE 2nd year i would like to thank you for providing all this information. keep rocking bro.

    ReplyDelete