Monday, October 22, 2012

Search Pattern in Java

Program to find a specific pattern from a given text or file is stated as below.



import java.io.*;

class srchPattern
{
  public static void main(String args[])
  {
    if(args.length == 0 || args.length == 1)
    {
      System.out.println("Insufficient arguments...");
      return;
    }

    File f = new File(args[1]);

    try
    {
      BufferedReader i = new BufferedReader(new FileReader(args[1]));

      String line;
      int ct = 0;

      if(f.exists() && f.isFile())
      {
        while((line = i.readLine()) != null)
        {
          if((line.indexOf(args[0])) != -1)
          {
            ct++;
          }
          System.out.println(line + " ");
        }

        if(ct == 0)
        {
          System.out.println("Pattern not Found");
        }
        else
        {
          System.out.println("Pattern found in the file...");
          System.out.println("Number of Occurances of the word " + args[0] + " in te file " + args[1] + " is " + ct);
        }
      }
    }
    catch(Exception e){}
  }
}

Word,character count in Java

Program  to count the number of occurrences of a word in a file is given as below:


import java.io.*;

class wordcnt
{
  public static void main(String args[])
  {
    int i = 0,cnt = 0;
    try
    {
      FileInputStream fin = new FileInputStream("d:/java/wordcnt.java");
      String word;
      char ch , charr[];
      charr = new char[100];
      String w = new String("word");
      while(( ch = (char)fin.read()) != -1)
      {
        if( ch != ' ' && ch != '\n')
        {
           charr[i] = ch ;
           i++;
        }
        else
        {
           word = new String(charr,0,i);
           if(word.equals(w))
              cnt++;   
           if( ch == '\n')
              System.out.println( word );
           else
              System.out.print( word + " ");
           i = 0;
        }
     };
     fin.close();
    }
    catch(Exception ie)
    {
    }
    System.out.println("\n\nWord Count : " + cnt);
  }
}

Copy file in Java

Program to copy a file content in java is as follows:

 import java.io.*;

class FileCopy
{
  public static void main(String args[]) throws IOException
  {
    FileInputStream fin = new FileInputStream("d:/java/stk.java");
    FileOutputStream fout = new FileOutputStream("d:/java/txtfile.txt");
    int b;

    while(true)
    {
      b = fin.read();
      if(b == -1)
      {
        break;
      }
      System.out.print((char)b);
      fout.write(b);
    }

    fin.close();
    fout.close();
  }
}

Polynomial operations in Java

Program for Ploynomial expression in java is as follows:


import java.lang.*;
import java.io.*;
class term
{
  int coeff,exp;
}
class poly
{
    term pl[] = new term[10];
    int n;
    poly()throws Exception
    {
        poly p[]=new poly[10];
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the no. of terms: ");
        n=Integer.parseInt(br.readLine());
    }
    public void getPoly()throws Exception
    {
        poly p[]=new poly[10];
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the base & exponent:");
        for(int i=0;i<n;i++)
        {
            p[i].coeff=Integer.parseInt(br.readLine());
            p[i].exp=Integer.parseInt(br.readLine());
        }
    }   
    public void putPoly()
    {
        poly p[]=new poly[10];
        System.out.println("Polynomial is : ");
        for(int i=0;i<n;i++)
        {
            System.out.println(" "+p[i].coeff+"x^"+p[i].exp);
        }
    }
    public void evalPoly()throws exception
    {
        poly p[]=new poly[10];
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int x,ans=0;
        System.out.println("Enter the value for x:");
         x=Integer.parseInt(br.readLine());   
        for(int i=0;i<n;i++)
        {
            ans=ans+p[i].coeff*pow(x,p[i].exp);
        }
        System.out.println("Ans : "+ans);
    }
    public static void main(String args[])throws Exception
    {
        poly p1=new poly();
        poly p2=new poly();
        p1.getPoly();
        p2.getPoly();
        p1.putPoly();
        p2.putPoly();
        p1.evalPoly();
       
    }   
}

Matrix in Java

Program for matrix in java is as follows:


import java.io.*;

class matrix
{
  int mat[][],r,c;

  matrix()
  {
     mat = new int[10][10];
  }
  public void getMat() throws Exception
  {
   // mat = new int[10][10];
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("\nEnter the Dim of the matrix : ");    
    r = Integer.parseInt(br.readLine());
    c = Integer.parseInt(br.readLine());

    System.out.println("\nEnter the matrix elements : ");    
    for(int i = 0 ; i < r ; i++)
    {
      for(int j = 0 ; j < c ; j++)
      {
        mat[i][j] = Integer.parseInt(br.readLine());
      }
    }
  }

  public void addMat(matrix m1,matrix m2)
  {
     r = m1.r;
     c = m1.c;

     for(int i = 0 ; i < r ; i++)
    {
       for(int j = 0 ; j < c ; j++)
       {
          mat[i][j] = m1.mat[i][j] + m2.mat[i][j];
       }
    }
  }

  public void putMat()
  {
    System.out.println("\nMatrix is : \n");
    for(int i = 0 ; i < r ; i++)
    {
      for(int j = 0 ; j < c ; j++)
      {
        System.out.print(" " + mat[i][j]);
      }
      System.out.println("");
    }
  }

  public static void main(String args[]) throws Exception
  {
    matrix m1 = new matrix();
    matrix m2 = new matrix();
    matrix m3 = new matrix();

    m1.getMat();
    m2.getMat();

    m1.putMat();
    m2.putMat();

    m3.addMat(m1,m2);
    m3.putMat();
  } 
}

Linear Search in Java

Below is simple program in java which shows the linear search.


import java.io.*;

class LinearSearch
{
  int ar[];
  int ele,n;

  public void setData() throws Exception
  {
     ar = new int[10];
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter the size for array : ");    
    n = Integer.parseInt(br.readLine());

    System.out.println("Enter the data for array : ");    
    for(int i = 0 ; i < n ; i++)
    {
      ar[i] = Integer.parseInt(br.readLine());
    }
    
    System.out.println("Enter the data to be searched : ");
    ele = Integer.parseInt(br.readLine());
  }

  public void putData()
  {
    System.out.println("The array is : ");
    for(int i = 0 ; i < n ; i++)
    {
      System.out.println(" " + ar[i]);
    }
  }

  public void LinSrch()
  {
    int i;
   
    for(i = 0 ; i < n ; i++)
    {
      if(ar[i] == ele)
      {
        break;
      }
    }
    if(i == ar.length)
    {
      System.out.println("\nElement not found");
    }
    else
    {
      System.out.println("\nElement found at " + i);
    }
  }

  public static void main(String args[]) throws Exception
  {
    LinearSearch ln = new LinearSearch();
    ln.setData();
    ln.putData();
    ln.LinSrch();
  }

}

Vector Demo in Java

Program for vector in java.

Below is the program.

import java.util.*;

class vectorDemo
{
    public static void main(String args[])
    {
        Vector v = new Vector(3,2);

        System.out.println("Intial Size : " + v.size());
        System.out.println("Intial Capacity : " + v.capacity());

        v.addElement(new Integer(1));
        v.addElement(new Integer(2));
        v.addElement(new Integer(3));
        v.addElement(new Integer(4));

        System.out.println("Capacity after 4 additions : " + v.capacity());
        v.addElement(new Double(4.55));
        System.out.println("Capacity after adding double element : " + v.capacity());       
    }
}

Array Keys and Array Values

Below is Simple Example which shows how the array keys or array values can be obtained from a array.


<?php

     $personinfo=array(array("name"=>"john","address"=>"pune","age"=>30),
          array("name"=>"Sathya","address"=>"Nashik","age"=>39),
          array("name"=>"madhav","address"=>"pune","age"=>22));

      $arr1=array_keys($personinfo);

      $arr2=array_values($personinfo);

       echo "OUTPUT AS ONLY KEYS FOR GIVEN ARRAY";
       echo "<br><br>";
       print_r($arr1);

      echo "<br><br>";   
      echo "OUTPUT AS ONLY VALUES FOR GIVEN ARRAY";
      echo "<br><br>";
      print_r($arr2);

?>

PHP Function to create slug from string

Here is simple Function to create slug from string.



function getSlug($title)
             {
                        $slug = preg_replace("/[^a-zA-Z0-9 ]/", "", $title);
                           $slug = str_replace(" ", "-", $slug);
                        $slug=strtolower($slug);
                        return($slug); 
  }

PHP Function to generate random unique string.

Here is a Simple Function to generate random unique string.



            function GenerateNumber($min, $max)
{
                        // Create the meta-password
                        $sMetaPassword = "";
                        global $CONFIG;
                        $ahPasswordGenerator = array(
                        "C" => array('characters' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'minimum' => $min, 'maximum' => $max),
//"S" => array('characters' => "!@()-_=+?*^&", 'minimum' => 2, 'maximum' => 2
"N" => array('characters' => '1234567890', 'minimum' => $min, 'maximum' => $max)
);
                        foreach ($ahPasswordGenerator as $cToken => $ahPasswordSeed)
$sMetaPassword .= str_repeat($cToken, rand($ahPasswordSeed['minimum'], $ahPasswordSeed['maximum']));
                                    $sMetaPassword = str_shuffle($sMetaPassword);
                        // Create the real password
                        $arBuffer = array();
                        for ($i = 0; $i < strlen($sMetaPassword); $i ++)
$arBuffer[] = $ahPasswordGenerator[(string)$sMetaPassword[$i]]['characters'][rand(0, strlen($ahPasswordGenerator[$sMetaPassword[$i]]['characters']) - 1)];
                        return implode("", $arBuffer);

PHP Function to check whether the given number is decimal or not.

Below is a simple Function to check whether the given number is decimal or not.



function check_decimal($dec_val, $decimals = 2)
{
                        $pattern = "/^[-]*[0-9][0-9]*\.[0-9]{".$decimals."}$/";
                        if (preg_match($pattern,  $dec_val))
                                    return true;
                        else
                                    return false;
}

PHP Function to check whether a given date is valid or not.

Here is a Simple Function to check whether a given date is valid or not.



           function is_valid_date($value, $separator='-')
{
              if(strlen($value) <= 10)
                        {
                        // check date
                        $arr=explode($separator,$value);
                        $day=$arr[2];
                        $month=$arr[1];
                        $year=$arr[0];
                        if(@checkdate($month, $day, $year))
                                    return true;
              }
             return false;
}

PHP Function to calculate days difference between given 2 dates.

Here is a simple  Function to calculate days difference between given 2 dates.



function daysDifference($endDate, $beginDate)
{

              //explode the date by "-" and storing to array
             $date_parts1=explode("-", $beginDate);
             $date_parts2=explode("-", $endDate);
             //gregoriantojd() Converts a Gregorian date to Julian Day Count
            $start_date=gregoriantojd($date_parts1[1], $date_parts1[2], $date_parts1[0]);
             $end_date=gregoriantojd($date_parts2[1], $date_parts2[2], $date_parts2[0]);
             return $end_date - $start_date;
}

PHP Function to convert date from mm/dd/yyyy to yyyy-mm-dd

Here is a simple Function to convert date from  mm/dd/yyyy to yyyy-mm-dd.



function convert_date($date)
{
                        if($date=='')
                        return '';
                     else
                        $dateArray=explode('/',$date);

                        return "$dateArray[2]-$dateArray[0]-$dateArray[1]";
}

PHP Function to validate an email address

Here is a simple Function to validate an email address in php.



function check_email($mail_address)
{
                        if($mail_address == '')
                        {
                                    return false;
                        }
                        else
                        {
if (preg_match("/^[0-9a-z]+(([\.\-_])[0-9a-z]+)*@[0-9a-z]+(([\.\-])[0-9a-z-]+)*\.[a-z]{2, 4}$/i",  strtolower($mail_address)))
                                    return true;
                        else
                                    return false;
                        }
}

PHP Function to get extension of a file.

Here is a simple function which returns the extension of the file.



           function getExtension($str)
{
                        $i = strrpos($str,".");
                        if (!$i) { return ""; }
                        $l = strlen($str) - $i;
                        $ext = substr($str,$i+1,$l);
                        return $ext;

Saturday, August 11, 2012

Create table in PostgreSQL.

In this Section we are going to learn that how are tables created in PostgreSQL.

First of all you need the PostgreSQL software installed on your computer. If you don't have no problem you can download from the following link. Choose your platform and you are ready to download.

Download :  PostgreSQL

OK after you download and install the software then run it from the command prompt as mentioned in the read me manual.

A screen will appear in front of you when you run the program by filling in the appropriate login or authentication information.

Then simple write the following lines on the screen and run it.

Type the two paragraphs A) and B) on your screen and run it.

A) Item Table

     create table item
      (item_no integer primary key,
      item_name text,
      qty float);

B) Supplier table.

     create table supplier
     (supp_no integer primary key,
     supp_name text,
     address text,
     city text,
     phoneno integer);

When you run these two codes in your command prompt two tables named Item  and Supplier will be created in your database.

Now we will insert data in these two tables. now Run the Following statements on your command prompt and data will be inserted in both tables.

C) Inserting Data in Item Table.

     insert into item values(1,'cdrom',1200);
     insert into item values(2,'cd writer',1500);
     insert into item values(3,'fdd',800);
     insert into item values(4,'hdd',3200);
     insert into item values(5,'speaker',1200);
     insert into item values(6,'usb',500);
     insert into item values(7,'mouse',500);
     insert into item values(8,'monitor',1200);





D) Inserting Data in Supplier table.


     insert into supplier values(1,'singh0','ozar0','nasik0',5602077);
     insert into supplier values(2,'singh1','ozar1','nasik1',5602076);
     insert into supplier values(3,'singh2','ozar2','nasik2',5602075);
     insert into supplier values(4,'singh3','ozar3','nasik3',5602074);
     insert into supplier values(5,'singh4','ozar4','nasik4',5602073);
     insert into supplier values(6,'singh5','ozar5','nasik5',5602072);
     insert into supplier values(7,'singh6','ozar6','nasik6',5602071);
     insert into supplier values(8,'singh7','ozar7','nasik7',5602070);*/
     insert into supplier values(9,'singh8','ozar8','nasik0',2775411);





PL/pgSql



The Full Form of PL/pg Sql is  Procedural language/Postgre Sql.
It is a Structured Query language. It is Almost Similar to Sql Queries but it is more structured and more easy than the Sql Commands and functions.

Specifications of the Pl/pg Sql is as Follows:

1) Database created has no Size Limit ie it can be unlimited.
2) The table created in it can have a maximum size of  32 TB and not more than that.
3) The maximum Row Size can be maximum  upto 1.6 TB and not more than that.
4) There can be any number of rows per tables .
5) It is Highly Customizable.

Postgres Sql is available under the liberal open source license(LOSL) to download and modify,distribute and use for development. It is a powerful tool that can be used for home applications, web development, ecommerce and at places where softwares or products of high RDBMS is required.

Below is a Simple example of Postgres sql function.



 
create table Doctor
    (
        doc_no        integer        primary key    ,
        doc_name     text        not null    ,
        address        text        not null    ,
        city        text        not null   
    );

create table Hospital
    (
        hosp_no        integer        primary key    ,
        hosp_name    text        not null    ,
        hosp_city    text        not null   
    );   

create table Doc_Hosp
    (
        doc_no        integer        references Doctor    ,
        hosp_no        integer        references Hospital   
    );

insert into Doctor values(1,'Mr. Chandan','Ram krishna Nagar','Nasik');
insert into Doctor values(2,'Mr. Rahul','Gagapur road','Pune');
insert into Doctor values(3,'Mr. Amit','Ojhar','Mumbai');
insert into Doctor values(4,'Mr. Prasanna','Trimurti','Nagpur');
insert into Doctor values(5,'Mr. Atul','Colony','Kanpur');

insert into Hospital values(1,'Grand Hospital','Nasik');
insert into Hospital values(2,'Charity Hospital','Pune');
insert into Hospital values(3,'Perfect Hospital','Nagpur');
insert into Hospital values(4,'Maya Hospital','Kanpur');
insert into Hospital values(5,'Hayat Hospital','Mumbai');

insert into Doc_Hosp values(1,2);
insert into Doc_Hosp values(1,3);
insert into Doc_Hosp values(1,4);
insert into Doc_Hosp values(1,5);
insert into Doc_Hosp values(2,3);
insert into Doc_Hosp values(2,4);
insert into Doc_Hosp values(3,5);
insert into Doc_Hosp values(4,4);
insert into Doc_Hosp values(5,3);
insert into Doc_Hosp values(5,1);


a) 
create or replace function ass1()
    returns text as'

declare
    cursor1 cursor for
            select doc_no,doc_name,city
            from doctor;
   
    cursor2 cursor(city text)  for
            select hosp_no
            from hospital
            where hospital.hosp_city <> city;

    cursor3 cursor(dno integer) for
            select *
            from doc_hosp
            where doc_hosp.doc_no = dno;
       
    temp1 record;           
    temp2 record;
    temp3 record;
    flag integer;
    output text := ''\n'';

begin
   
    open cursor1;
    loop
        fetch cursor1 into temp1;
        exit when not found;   

        flag := 1;
       
        open cursor2(temp1.city);
        loop
            fetch cursor2 into temp2;   
            exit when not found;

            open cursor3(temp1.doc_no);
            loop
                fetch cursor3 into temp3;   
                exit when not found;

                if(temp2.hosp_no = temp3.hosp_no) then
                    flag := 1;
                output := output||''Match found : ''||temp2.hosp_no||''\n'';
                    exit;   
                else
                    flag := 0;
                end if;
            end loop;
            close cursor3;   -- cursor3 end

            if(flag = 0) then
                exit;
            end if;   
        end loop;
        close cursor2;  -- cursor2 end

        if(flag = 1) then
            output := output || temp1.doc_name ||''\n'';
        end if;
    end loop;
    close cursor1;    -- cursor1 end

    return output;
end;

'language plpgsql

/*
    OUTPUT 

SLIP=# select ass1();
     ass1
---------------
 
Mr. Chandan

(1 row)

*/



b)   create or replace function ass2()returns text as'

declare
    cursor1 cursor for
            select doc_no,doc_name
            from doctor;   

    cursor2 cursor(dno integer) for
            select *
            from doc_hosp
            where doc_hosp.doc_no = dno;

    temp3 hospital %rowtype;
    temp1 record;
    temp2 record;
    output text := ''\n'';

begin
    open cursor1;
    loop
        fetch cursor1 into temp1;
        exit when not found;

        output := output || temp1.doc_name || ''\n'';

        open cursor2(temp1.doc_no);
        loop
            fetch cursor2 into temp2;
            exit when not found;   

            for temp3 in select * from hospital where hospital.hosp_no = temp2.hosp_no
            loop
                 output := output ||''\t''||temp3.hosp_name||''\n'';
            end loop; -- close for temp3
        end loop;
        close cursor2; -- close cursor2
    end loop;   
    close cursor1; -- close cursor1

    return output;
end;

'language plpgsql;
/*

    OUTPUT

SLIP=# select ass2();
                                                                                                             ass2                                                                                                    
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 
Mr. Chandan
        Charity Hospital
        Perfect Hospital
        Maya Hospital
        Hayat Hospital
Mr. Rahul
        Perfect Hospital
        Maya Hospital
Mr. Amit
        Hayat Hospital
Mr. Prasanna
        Maya Hospital
Mr. Atul
        Perfect Hospital
        Grand Hospital

(1 row)

*/

Wednesday, August 8, 2012

Linklist in Java

Here is simple Link List program in java.

import java.util.*;

class linklist
{
    public static void main(String args[])
    {
        LinkedList l1 = new LinkedList();
        LinkedList l2 = new LinkedList();
        LinkedList l3 = new LinkedList();
        LinkedList l4 = new LinkedList();
        int i,j;
      
        l1.add("a");
        l1.add("b");
        l1.add("c");
        l1.add("d");
        l1.add("e");
      
        l2.add("a");
        l2.add("c");
        l2.add("e");
        l2.add("g");
        l2.add("i");

        System.out.print("Intersection of link list : ");
        for(i = 0 ; i < 5 ; i++)
        {
            for(j = 0 ; j < 5 ; j++)
            {
                if(l1.get(i).equals(l2.get(j)))
                {
                    l3.add(l1.get(i));
                    break;
                }
            }
        }
        System.out.print(l3);
      
        System.out.print("\nUnion of list : ");
        for(i = 0 ; i < 5 ; i++)
        {
            l4.add(l1.get(i));
        }  
        for(i = 0 ; i < 5 ; i++)
        {
             for(j = 0 ; j < 5 ; j++)
             {
                 if(l2.get(i).equals(l1.get(j)))
                 {
                     break;
                 }
             }
             if(j == 5)
             {
                 l4.add(l2.get(i));
             }
        }
        System.out.print(l4);
    }
}

Dialog box in Java

Java Program which displays a dialog box on body load(Page Load).

import java.awt.*;
import java.awt.event.*;


public class msgDialog extends Frame
{
  msgDialog()
  {
    messageBox mb = new messageBox(this,"This is a Simple Dialog Box!!!");
    mb.setLocation(200,200);
    mb.setVisible(true);
  }
 
  public static void main(String args[])
  {
    msgDialog md = new msgDialog();
    System.out.println("Displaying Dialog Box....");
    md.setVisible(true);
  }
}

Message Box in Java

Display a Message box in Java on Button Click.

import java.awt.*;
import java.awt.event.*;

public class messageBox extends Dialog
{
  Button b1,b2;
  messageBox(Frame fm,String lab)
  {
    super(fm,"Message",true);
    setLayout(new GridLayout(2,1,0,0));

    Panel p1 = new Panel();
    Panel p2 = new Panel();

    p1.setLayout(new FlowLayout(FlowLayout.CENTER,20,15));
    p2.setLayout(new FlowLayout(FlowLayout.CENTER,20,15));

    p1.add(new Label(lab));

    b1 = new Button("Ok");
    b1.addActionListener(new B1());
    p2.add(b1);

    b2 = new Button("Cancel");
    b2.addActionListener(new B1());
    p2.add(b2);

    add(p1);
    add(p2);

    setSize(350,125);
    addWindowListener(new WindowAdapter()
    {
      public void windowClosing(WindowEvent we)
      {
        System.exit(0);
      }
    });
  }

  class B1 implements ActionListener
  {
    public void actionPerformed(ActionEvent ae)
    {
      try
      {
        //Button ok = (Button)ae.getSource();
        //String s = ok.getLabel();
        if(ae.getSource() == b1 || ae.getSource() == b2)
        {
      System.out.println("Button Clicked");
      dispose();
      System.exit(0);
        }
      }
      catch(Exception e){} 
    }
  }
}

Servlet Session in Java

Here is a simple servlet program which display session information.

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class sessionInfo extends HttpServlet
{
  public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
  {
    HttpSession mySession = req.getSession(true);
   
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
   
    out.println("<HTML><BODY>");
    out.println("<h3>Session Information</H3>");
    out.println("<BR>New Session    : " + mySession.isNew());
    out.println("<BR>Session ID : " + mySession.getId());
    out.println("<BR>Session Creation Time : " + mySession.getCreationTime());
    out.println("<BR>Session Last Accessed Time : " + mySession.getLastAccessedTime());

    out.println("<BR><H3>Request Information</H3>");
    out.println("<BR>Session ID from Request : " + req.getRequestedSessionId());
    out.println("<BR>Session ID via Cookie : " + req.isRequestedSessionIdFromCookie());
    out.println("<BR>Valid Session ID : " + req.isRequestedSessionIdValid());

    out.println("</BODY></HTML>");
    out.close();
  }
}

Animation in Java

Here is a Simple Animation Program in Java.

import java.awt.*;
import java.awt.event.*;

public class Animation extends Frame implements ActionListener,Runnable
{
    Button bStart,bExit;
    int i,j;
    Thread t;
    public Animation()
    {
        bStart = new Button("Start");
        bExit = new Button("Exit");
       
        setLayout(new FlowLayout());
        add(bStart);
        add(bExit);
       
        bStart.addActionListener(this);
        bExit.addActionListener(this);
    }
   
    public void run()
    {
        try
        {
            j = 0;
            for(i = 0 ; i < 100 ; i = i + 2)
            {
                paint(getGraphics());
                t.sleep(100);
            }
            i=50;
            for(j = 0 ; j < 100 ; j = j + 2)
            {
                paint(getGraphics());
                t.sleep(100);
            }
        }
        catch(Exception e){}
    }
   
    public void start1()
    {
        t = new Thread(this);
        try
        {       
            t.start();
        }
        catch(Exception e)
        {
            System.out.println("Exception Occured : " + e);
        }
    }
   
    public void paint(Graphics g)
    {
        //Color c = new Color(i);
        //setForeground(c);
        //g.setColor(Color.BLUE);
        g.clearRect(0,0,this.getHeight(),this.getWidth());
        g.drawOval(50+j,50+i,30,30);       
        return;
    }

    public void actionPerformed(ActionEvent ae)
    {
        if(ae.getSource() == bExit)
        {
            System.exit(1);
        }
        if(ae.getSource() == bStart)
        {
            System.out.println("Start Button Clicked...");
            start1();
        }
   
    }
    public static void main (String[] args)
    {   
        Animation a1 = new Animation();
        a1.setSize(400,400);
        a1.show();
    }
}

Menu Driven Program in Java

 A menu driven system which will perform following options for student data
 1) (Roll No,Name,Per)
 2) Insert, Update, Delete, Search  record
 3) Raise Exception if wrong data are entered like negative for roll no.

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

 class NegativeNumberException extends Exception  { }


 class Slip5_9_13_2
 {
     public static void main(String agrs[]) throws IOException
     {
    
       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       Student stud;
  &stud);
                       break;
                case 2:System.out.print("\nEnter Position where to insert record : ");
                        pos=Integer.parseInt(br.readLine());
         System.out.println("|------------------------------|");
         System.out.println("|\t [1] :Add \t\t|");
         System.out.println("|\t [2] :Insert \t\t|");
         System.out.println("|\t [3] :Update \t\t|");
         System.out.println("|\t [4] :Search \t\t|");
         System.out.println("|\t [5] :Delete \t\t|");
         System.out.println("|\t [6] :Print \t\t|");
         System.out.println("|\t [7] :Exit \t\t|");
          System.out.println("|------------------------------|");
         System.out.print("\nEnter Choice : ");
        
        
         try
          {
              ch=Integer.parseInt(br.readLine());
             
               switch(ch)
              {
                case 1:System.out.println("\nEnter Stud Details\n");
                       stud=new Student();
                       perfect=stud.read_data();   
                       if(perfect==1)
                           L.add(stud);
                       break;
                case 2:System.out.print("\nEnter Position where to insert record : ");
                        pos=Integer.parseInt(br.readLine());
                       if(pos>L.size())
                         {
                              System.out.println("\n\nPosition out of range\n\n");
                              break;
                         }   
                      
                       stud= new Student();
                       perfect=stud.read_data();
                       if(perfect==1)
                            L.add(pos,stud);
                       break;
                 case 3:System.out.print("\n Enter Roll no to update record : ");
                        no=Integer.parseInt(br.readLine());
                        found=0;
                        it=L.iterator();
                         while(it.hasNext())
                         {
                           stud=(Student)it.next();
                           if(stud.rno==no)
                              {
                                 found=1;   
                                  pos=L.indexOf(stud);
                                L.remove(pos);// remove old record from specified pos
                               
                                perfect=stud.read_data();
                               
                                if(perfect==1)
                                     L.add(pos,stud);
                            
                                break;
                               }
                         } 
                       if(found!=0)  //found==0
                           System.out.println("\nRoll_No not present so Record Not Updated ");
                                               
                       break;        
                              
                case 4:System.out.print("Enter Rollno to search record : ");
                       no=Integer.parseInt(br.readLine());
                       found=0;
                       it=L.iterator();
                      
                       while(it.hasNext())
                       {
                           stud=(Student)it.next();
                            if(stud.rno==no)
                              {
                                  found=1;
                                  pos=L.indexOf(stud);
                                  System.out.println("\n\nReord Found at "+pos+" Position\n");
                                  stud.show_data();
                                 
                                  break;
                                 
                              }
                       }
                       if(found!=1)
                             System.out.println("\nRoll_No not present so Record Not Found");
                         
                      break;
                     
                case 5:System.out.print("\n Enter Roll no to delete record : ");
                        no=Integer.parseInt(br.readLine());
                        found=0;
                        it=L.iterator();
                       
                        while(it.hasNext())
                         {
                          stud=(Student)it.next();
                              if(stud.rno==no)
                            {
                                 found=1;
                                 L.remove(stud);
                                 System.out.print("\nRecord deleted succesfully \n");
                                 break;   
                               }
                         }
                        if(found!=1)
                          System.out.println("\nRoll_No not present so Record Not Deleted\n");
                        
                       break;
            
                case 6:System.out.println("\n\n|------* Student Details *-----|");
                       System.out.println("|------------------------------|");
                      System.out.println("|ROLL NO\t NAME\t PERCENTAGE|");
                      System.out.println("|------------------------------|");

                      it=L.iterator();

                      while(it.hasNext())
                       {
                             stud=(Student)it.next();
                             stud.show_data();
                       }
                      System.out.println("|------------------------------|");
                      break;
                case 7:System.exit(0);           
               
            
              }//switch
           }
         catch(NumberFormatException n)
         {   System.out.println("Exception "+n); }
        
       }while(ch!=7);
     }//main
    
 }// class slip


 class Student
 {
     BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
     int rno;    // Roll no
     String name; //name
     double per;//percentage
    
     int  read_data() throws IOException
     {
         try
         {
        
             System.out.print("Roll No : ");
             rno=Integer.parseInt(br.readLine());
                if(rno<0)
                   throw new NegativeNumberException();
           
             System.out.print("Name : ");
             name=br.readLine();
            
             System.out.print("Percentage : ");
             per=Double.parseDouble(br.readLine());
                 if(per<0)
                     throw new NegativeNumberException();
            
          }
         
         catch(NegativeNumberException n)
         {
          System.out.println("Exception: Number Must be Positive");
           return 0;
         } 
       return 1;    
       
      }// read_data()
     
      void show_data()
      {
          System.out.println("| "+rno+"\t | "+name+" | "+per+" |");
      }  

 }

File Watcher Program in Java

Java Program to create a class called File Watcher that can be given several file names
that may or may not exist. the class should start a thread for each file name
Each thread will periodically check for the existence of it's file.
If the file exist,the thread will write a message to the console & then end.

import java.io.*;
class SlipFileWatch
{
 public static void main(String args[]) throws IOException
  {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("\n Enter Several N  files");
        try
        {
          int n =Integer.parseInt(br.readLine());
          System.out.println("\n Enter File name");
          for(int i=1;i<=n;i++)
                  new FileWatcher(br.readLine());
        }  
        catch(Exception e)
        { System.out.println("Invalid Input");}
    }
}   
   
class FileWatcher implements Runnable
{
    Thread T;
    String fname;
    FileWatcher(String fn)
    {
        fname=fn;
        T=new Thread(this,fname);
        System.out.println("\n\nNew = "+T);
        T.start();
    }
   
    public void run()
    {
        File f = new File(fname);
        if(f.exists())
          System.out.println(" "+fname+"  File Exist ");
        else 
          System.out.println(" "+fname+"  File Not Exist");
         try
          {
              Thread.sleep(1000);
          }
          catch(InterruptedException it){}
    }
}

Multiple Select Box and Combo box in Java

The java program given below does the following tasks,

 1) Button(<<) moves all items from list1 to list2.
 2) Button(<) moves single item from list1 to list2.
 3) Button(>>) moves all items from list2 to list1.
 4)Button(>) moves single item from list2 to list1.
  5)When 1 item is moved the next item should be highlighted automatically.
  6)No list box should contain duplicate entries
  7)Add & Remove button should work for their own list box & not for other

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

public class Slip2_1 extends JFrame implements ActionListener
{
    List list1,list2;
    JButton b1,b2,b3,b4,b5,b6,b7,b8;
   
    JTextField t1;
  
    int i,j;
   // String d;
  
   

    public static void main(String args[])
       {
               Slip2_1  s = new Slip2_1();
              
       }
   
   // Container c=getContentPane();
       
    public Slip2_1()
    {
       
        super("List add/remove item ");
       
        setSize(550,450);
        setLocation(100,100);
        //setBounds(100,100,550,450);
        setVisible(true);
        setLayout(null);
       
        list1 = new List();
        list1.add("Ball");
        list1.add("Bat");
        list1.add("Stump");
        list1.add("Pad");
        list1.add("Gloves");
        list1.add("Shoes");
        list1.add("Helemet");
        list1.add("Bells");
        list1.add("Caps");
        list1.add("Medicine");
        list1.setBounds(75,100,90,200);
        add(list1);
       
        list2 = new List();
        list2.add("Computer");
        list2.add("Laptop");
        list2.add("Camera");
        list2.add("Veg");
        list2.add("Non_Veg");
        list2.add("Medicine");
        list2.setBounds(350,100,100,200);
        add(list2);
       
        b1 =new JButton("<<");
        b1.setBounds(225,100,75,25);
        add(b1);
       
        b2 =new JButton("<");
        b2.setBounds(225,150,75,25);
        add(b2);
       
        b3 =new JButton(">>");
        b3.setBounds(225,200,75,25);
        add(b3);
       
        b4 =new JButton(">");
        b4.setBounds(225,250,75,25);
        add(b4);
       
        //list1
        b5 =new JButton("Add");
        b5.setBounds(25,350,75,25);
        add(b5);
       
        b6 =new JButton("Remove");
        b6.setBounds(150,350,85,25);
        add(b6);
       
       
        //list2
        b7 =new JButton("Add");
        b7.setBounds(325,350,75,25);
        add(b7);
       
        b8 =new JButton("Remove");
        b8.setBounds(425,350,85,25);
        add(b8);
        
        
        b1.addActionListener(this) ;
        b2.addActionListener(this);
        b3.addActionListener(this) ;
        b4.addActionListener(this) ;
        b5.addActionListener(this);
        b6.addActionListener(this) ;
        b7.addActionListener(this) ;
        b8.addActionListener(this) ;
        
       
    }//slip2_1 constructor

 public void actionPerformed(ActionEvent ae)   
 {
    
    
     if(ae.getSource()==b1) // list1 << list2
     {
      // << copy all item from list1 to list2
     int cnt1 = list1.getItemCount();
     int cnt2 = list2.getItemCount();
     for(int i=0;i<cnt1;i++)
      {
       int flag=0;
        for(int j=0;j<cnt2;j++)
          if(list1.getItem(i).equalsIgnoreCase(list2.getItem(j))==true)
             {
                      flag=1;
                      break;
            }

          if(flag==0)
           list2.add(list1.getItem(i));
       }
      list1.removeAll();    
       } // b1 list1 << list2
    
    
     if(ae.getSource()==b3) // list2 >> list1
     {
      //  copy all item from list2 to list1
       
     int cnt1 = list1.getItemCount();
     int cnt2 = list2.getItemCount();
     for(int i=0;i<cnt2;i++)
      {
       int flag=0;
        for(int j=0;j<cnt1;j++)
          if(list1.getItem(j).equalsIgnoreCase(list2.getItem(i))==true)
             {
                      flag=1;
                      break;
            }

          if(flag==0)
           list1.add(list2.getItem(i));
       }
      list2.removeAll();    
       }// b3  list1 >> list2
    
  String d;

   if(ae.getSource()==b2) // list1 < list2
   {
       // add single selected item from list1 to list2
       d =list1.getSelectedItem();
       int cnt = list2.getItemCount();
       for(i=0;i<cnt;i++)
        {
           if(list2.getItem(i).equals(d)) // d is selcted item from list1
            return;
        }
       list2.add(d);
      
   }// b2 list1 < list2


 if(ae.getSource()==b4) // list1 > list2
   {
       // add single selected item from list2 to list1
       d =list2.getSelectedItem();
       int cnt = list1.getItemCount();
       for(i=0;i<cnt;i++)
        {
           if(list1.getItem(i).equals(d)) // d is selcted item from list1
            return;
        }
       list1.add(d);
      
   }// b4 list1 > list2
  
  
   if(ae.getSource()==b5)
            {
                 String m = "Enter the item";
                 String result  =JOptionPane.showInputDialog(m);
                 int cnti=0,cnt = list1.getItemCount();
                
                 if(result!=null)
                 if(result.equals("")!=true)
                   {
                     for(int i=0;i<cnt;i++)
                      {
                        if(result.equalsIgnoreCase(list1.getItem(i))==true)
                         {cnti=1; break;}
                      }
                    if(cnt==0 || cnti==0)
                    list1.add(result);
                  }
            }

         if(ae.getSource()==b6)
            {
                String m = "Enter the item";
                String result  = JOptionPane.showInputDialog(m);
                   list1.remove(result);
               }

           if(ae.getSource()==b7)
               {
            String res=JOptionPane.showInputDialog("Enter The Item");
                int cnti=0,cnt = list2.getItemCount();
           
                           
                if(res!=null)
                if(res.equals("")!=true)
                 {
                   for(int i=0;i<cnt;i++)
                    {
                      if(res.equalsIgnoreCase(list2.getItem(i))==true)
                       {cnti=1; break;}
                    }
                   if(cnt==0 || cnti==0)
                   list2.add(res);
                 }
              }

         if(ae.getSource()==b8)
             {
              String res= JOptionPane.showInputDialog("Enter the item");
                list2.remove(res);
             }

  
  

    
 }//actionperformed
   
}

MS SQL : How to identify fragmentation in your indexes?

Almost all of us know what fragmentation in SQL indexes are and how it can affect the performance. For those who are new Index fragmentation...