Saturday 30 July 2016

Bubble Sort

bubble sort
import java.io.*;
class Bubblesort
{
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=0,i,j,t;
int a[]=new int[10];
System.out.println("Enter size of the array:");
try
{
n=Integer.parseInt(br.readLine());
}
catch(Exception e) {}
System.out.println("Enter elements into the array:");
try
{
for(i=0;i<n;i++)
a[i]=Integer.parseInt(br.readLine());
}
catch(Exception e) {}
for(i=0;i<n-1;i++)
for(j=0;j<n-1-i;j++)
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
System.out.println("The sorted array is:");
for(i=0;i<n;i++)
System.out.println(a[i]);
}
}
Output:
javac Bubblesort.java
java Bubblesort
Enter the size of array
5
Enter the elements into the array
45
34
76
12
69
The sorted array is
12 34 45 69 76

Selection sort

selection sort
import java.io.*;
class Selectionsort
{
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=0,i,j,t;
int a[]=new int[10];
System.out.println("Enter size of the array:");
try
{
n=Integer.parseInt(br.readLine());
}
catch(Exception e){}
System.out.println("Enter elements into the array:");
try
{
for(i=0;i<n;i++)
a[i]=Integer.parseInt(br.readLine());
}
catch(Exception e){}
i=0;
while(i<n-1)
{
int key=i;
for(j=i+1;j<n;j++)
{
if(a[j]<a[key])
{
key=j;
}
}
t=a[key];
a[key]=a[i];
a[i]=t;
i++;
}
System.out.println("The sorted array is:");
for(i=0;i<n;i++)
System.out.println(a[i]);
}
}


Output:
javac Selectionsort.java
java Selectionsort
Enter the size of array
5
Enter the elements into the array
45
34
76
12
69
The sorted array is
76 69 45 34 12

Binary Search

Binary Search
import java.lang.*;
import java.util.*;
import java.io.*;
class Search
{
public int binarysearch(int[]a,int key)
{
int f=1;
int low=0;
int high=a.length-1;
int mid=(low+high)/2;
while(low<=high)
{
if(a[mid]==key)
{
f=0;
break;
}
if(a[mid]<key)
low=mid+1;
else
high=mid-1;
mid=(low+high)/2;
}
return(f);
}
}
class Binarysearch
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
Search s=new Search();
int[]a;
int i,k,n;
int f=1;
System.out.println("Binary search");
System.out.println("enter your choice");
System.out.println("Enter the size of array");
n=sc.nextInt( );
a=new int[n];
System.out.println("Enter the elements");
for(i=0;i<n;i++)
a[i]=sc.next();
System.out.println("Enter the element to search:");
k=sc.nextInt();
int c=s.binarysearch(a,k);
if(c==0)
System.out.println("The element is found");
else
System.out.println("The elements is not found");
}
}


Output:
javac Binarysearch.java
java Binarysearch
BINARY SEARCH
Enter your choice
Enter the size of array
5
Enter the elements into the array
2
4
1
8
9
Enter the element to search
8
The element is found
Output:
javac Binarysearch.java
java Binarysearch
BINARY SEARCH
Enter your choice
Enter the size of array
5
Enter the elements into the array
2
4
1
8
9
Enter the element to search
10
The element not found

Linear search

 Linear search
import java.lang.*;
import java.util.*;
import java.io.*;
class Search
{
public int linearsearch(int[]a,int key)
{
int flag=1;
for(int i=0;i<a.length;i++)
{
if(a[i]==key)
{
flag=0;
}
}
return(flag);
}
}
class Linearsearch
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
{
Search s=new Search( );
int []a;
int i,k,n,ch;
int f=1;
System.out.println("Linear Search\n");
System.out.println("Enter the size of array");
n=sc.nextInt( );
a=new int[n];
System.out.println("enter the elements");
for (i=0;i<n;i++)
a[i]=sc.nextInt( );
System.out.println("enter the element to search");
k=sc.nextInt( );
f=s.linearsearch(a,k);
if(f==0)
System.out.println("The element is found");
else
System.out.println("Element is not found");
}
}
}


Output:
javac Linearsearch.java
java Linearsearch
LINEAR SEARCH
Enter your choice
Enter the size of array
5
Enter the elements into the array
2
4
1
8
9
Enter the element to search
8
The element is found
Output:
javac Linearsearch.java
java Linearsearch
LINEAR SEARCH
Enter your choice
Enter the size of array
5
Enter the elements into the array
2
4
1
8
9
Enter the element to search
10
The element not found

Friday 29 July 2016

Java program to add information to ms-access

Java program to add information to ms-access



 CREATE A DATABASE  "addItemDB.mdb" IN MS-ACCESS.
CREATE A TABLE "persons" with the following fields
id- Auto Number
firstName-Text
middleName-Text
familyName-Text
Age- Number
SAVE THE DATABASE.


TYPE THE FOLLOWING CODE IN THE NOTEPAD AND RUN THE PROGRAM

//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class addItemToDatabase extends JFrame {
   
    //Initializing Components
    private JTextField inputs[];
    private JButton add, reset;
    private JLabel labels[];
    private String fldLabel[] = {"First Name: ","Middle Name: ","Family Name: ","Age: "};
    private JPanel p1;
   
    Connection con;
    Statement st;
    ResultSet rs;
    String db;

    //Setting up GUI
    public addItemToDatabase() {
       
        //Setting up the Title of the Window
        super("Adding Data to the Database");

        //Set Size of the Window (WIDTH, HEIGHT)
        setSize(300,180);

        //Exit Property of the Window
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       
        //Constructing Components
        inputs = new JTextField[4];
        labels = new JLabel[4];
        add = new JButton("Add");
        reset = new JButton("Reset");
        p1 = new JPanel();
       
        //Setting Layout on JPanel 1 with 5 rows and 2 column
        p1.setLayout(new GridLayout(5,2));

        //Setting up the container ready for the components to be added.
        Container pane = getContentPane();
        setContentPane(pane);

        //Setting up the container layout
        GridLayout grid = new GridLayout(1,1,0,0);
        pane.setLayout(grid);
       
        //Creating a connection to MS Access and fetching errors using "try-catch" to check if it is successfully connected or not.
        try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                db = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=addItemDB.mdb;";
                con = DriverManager.getConnection(db,"","");
                st = con.createStatement();       
               
                JOptionPane.showMessageDialog(null,"Successfully Connected to Database","Confirmation", JOptionPane.INFORMATION_MESSAGE);
               
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null,"Failed to Connect to Database","Error Connection", JOptionPane.ERROR_MESSAGE);
                System.exit(0);
            }
       
        //Constructing JLabel and JTextField using "for loop" in their desired order
        for(int count=0; count<inputs.length && count<labels.length; count++) {
            labels[count] = new JLabel(fldLabel[count]);
            inputs[count] = new JTextField(20);
           
            //Adding the JLabel and the JTextFied in JPanel 1
            p1.add(labels[count]);
            p1.add(inputs[count]);
        }
       
        //Implemeting Even-Listener on JButton add
        add.addActionListener(
        new ActionListener() {
           
            //Handle JButton event if it is clicked
            public void actionPerformed(ActionEvent event) {
               
                if (inputs[0].getText().equals("") || inputs[1].getText().equals("") || inputs[2].getText().equals("") || inputs[0].getText() == null || inputs[1].getText() == null || inputs[2].getText() == null)
                    JOptionPane.showMessageDialog(null,"Fill up all the Fields","Error Input", JOptionPane.ERROR_MESSAGE);
                   
                else
                   
                try {
                   
                    String add = "insert into person (firstName,middleName,familyName,age) values ('"+inputs[0].getText()+"','"+inputs[1].getText()+"','"+inputs[2].getText()+"',"+inputs[3].getText()+")";
                    st.execute(add); //Execute the add sql
                   
                    Integer.parseInt(inputs[3].getText()); //Convert JTextField Age in to INTEGER
                   
                    JOptionPane.showMessageDialog(null,"Item Successfully Added","Confirmation", JOptionPane.INFORMATION_MESSAGE);
                   
                }catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(null,"Please enter an integer on the Field AGE","Error Input", JOptionPane.ERROR_MESSAGE);
                }catch (Exception ei) {
                    JOptionPane.showMessageDialog(null,"Failure to Add Item. Please Enter a number on the Field AGE","Error Input", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
        );
       
        //Implemeting Even-Listener on JButton reset
        reset.addActionListener(
        new ActionListener() {
           
            //Handle JButton event if it is clicked
            public void actionPerformed(ActionEvent event) {
                inputs[0].setText(null);
                inputs[1].setText(null);
                inputs[2].setText(null);
                inputs[3].setText(null);
            }
        }
        );
       
        //Adding JButton "add" and "reset" to JPanel 1 after the JLabel and JTextField
        p1.add(add);
        p1.add(reset);
       
        //Adding JPanel 1 to the container
        pane.add(p1);
       
        /**Set all the Components Visible.
         * If it is set to "false", the components in the container will not be visible.
         */
        setVisible(true);
    }
   
    //Main Method
    public static void main (String[] args) {
        addItemToDatabase aid = new addItemToDatabase();
    }
}

Retrieving data from the database

Retrieving data from the database



CREATE A DATABASE  "addItemDB.mdb" IN MS-ACCESS.
CREATE A TABLE "persons" with the following fields
id- Auto Number
firstName-Text
middleName-Text
familyName-Text
Age- Number
SAVE THE DATABASE.

TYPE THE FOLLOWING CODE IN THE NOTEPAD AND RUN THE PROGRAM




//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class retrieveDBUsingJList extends JFrame {
  
    //Initializing program components
    private DefaultListModel model;
    private JButton buttons[];
    private JList dbList;
    private JPanel p1,p2;
    private String bLabel[] = {"ID","First Name","Middle Name","Last Name","Age"};
  
    Connection con;
    Statement st;
    ResultSet rs;
    String db;

    //Setting up GUI
    public retrieveDBUsingJList() {
      
        //Setting up the Title of the Window
        super("Retrieve DB and Display Using JList");

        //Set Size of the Window (WIDTH, HEIGHT)
        setSize(300,200);

        //Exit Property of the Window
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              
        //Constructing JButtons, JList, and DefaultListModel
        model = new DefaultListModel();
        buttons = new JButton[5];
        dbList = new JList(model);
      
        //Setting up JList property
        dbList.setVisibleRowCount(5);
        dbList.setFixedCellHeight(27);
        dbList.setFixedCellWidth(130);
        dbList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      
        //Constructing JPanel 1 and its property
        p1 = new JPanel();
        p1.setBorder(BorderFactory.createTitledBorder("Database: "));
        p1.add(new JScrollPane(dbList)); //Adding JList in JPanel 1
      
        //Constructing JPanel 2 and its property
        p2 = new JPanel();
        p2.setLayout(new GridLayout(5,1));
        p2.setBorder(BorderFactory.createTitledBorder("Display: "));
      
        //Constructing all 5 JButtons using "for loop" and add it in JPanel 2
        for(int count=0; count<buttons.length; count++) {
            buttons[count] = new JButton(bLabel[count]);
            p2.add(buttons[count]);
        }
      
        //Setting up the container ready for the components to be added.
        Container pane = getContentPane();
        setContentPane(pane);

        //Setting up the container layout
        GridLayout grid = new GridLayout(1,2);
        pane.setLayout(grid);
      
        //Creating a connection to MS Access and fetch errors using "try-catch" to check if it is successfully connected or not.
        try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                db = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=addItemDB.mdb;";
                con = DriverManager.getConnection(db,"","");
                st = con.createStatement();      
              
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null,"Failed to Connect to Database","Error Connection", JOptionPane.WARNING_MESSAGE);
                System.exit(0);
            }
          
        //Implemeting Even-Listener on JButton buttons[0] which is ID
        buttons[0].addActionListener(
        new ActionListener() {
          
            //Handle JButton event if it is clicked
            public void actionPerformed(ActionEvent event) {
                try {
                    model.clear();
                    rs=st.executeQuery("select * from person");
                    while (rs.next()) {
                        model.addElement(rs.getString("id"));
                    }
                  
                } catch (Exception e) {
                    System.out.println("Retrieving Data Fail");
                }
            }
        }
        );
      
        //Implemeting Even-Listener on JButton buttons[1] which is First Name
        buttons[1].addActionListener(
        new ActionListener() {
          
            //Handle JButton event if it is clicked
            public void actionPerformed(ActionEvent event) {
                    try {
                    model.clear();
                    rs=st.executeQuery("select * from person");
                    while (rs.next()) {
                        model.addElement(rs.getString("firstName"));
                    }
                  
                } catch (Exception e) {
                    System.out.println("Retrieving Data Fail");
                }
            }
        }
        );
      
        //Implemeting Even-Listener on JButton buttons[2] which is Middle Name
        buttons[2].addActionListener(
        new ActionListener() {
          
            //Handle JButton event if it is clicked
            public void actionPerformed(ActionEvent event) {
                    try {
                    model.clear();
                    rs=st.executeQuery("select * from person");
                    while (rs.next()) {
                        model.addElement(rs.getString("middleName"));
                    }
                  
                } catch (Exception e) {
                    System.out.println("Retrieving Data Fail");
                }
            }
        }
        );
      
        //Implemeting Even-Listener on JButton buttons[3] which is Last Name
        buttons[3].addActionListener(
        new ActionListener() {
          
            //Handle JButton event if it is clicked
            public void actionPerformed(ActionEvent event) {
                    try {
                    model.clear();
                    rs=st.executeQuery("select * from person");
                    while (rs.next()) {
                        model.addElement(rs.getString("familyName"));
                    }
                  
                } catch (Exception e) {
                    System.out.println("Retrieving Data Fail");
                }
            }
        }
        );
      
        //Implemeting Even-Listener on JButton buttons[4] which is Age
        buttons[4].addActionListener(
        new ActionListener() {
          
            //Handle JButton event if it is clicked
            public void actionPerformed(ActionEvent event) {
                    try {
                    model.clear();
                    rs=st.executeQuery("select * from person");
                    while (rs.next()) {
                        model.addElement(rs.getString("age"));
                    }
                  
                } catch (Exception e) {
                    System.out.println("Retrieving Data Fail");
                }
            }
        }
        );
               
        //Adding components to the container
        pane.add(p1);
        pane.add(p2);
      
        /**Set all the Components Visible.
         * If it is set to "false", the components in the container will not be visible.
         */
        setVisible(true);
        setResizable(false);
    }
  
    //Main Method
    public static void main (String[] args) {
        retrieveDBUsingJList rdjl = new retrieveDBUsingJList();
    }
}