Wednesday 21 November 2012

NQueen problem in C

Today I am going to post the NQueen problem in C with Backtracking.
What is the problem : According to this problem, we will have to place N queens in a n*n chessboard in such a way that the quuens are non-attacking. Non-attacking means there should be no queens in the same row,column or diagonal.
How to solve the problem : Here we will use the method of backtracking. In order to solve this problem, we first place the first queen, then the second and so on. But if we fail to place a queen, then we go back to the last successful position and try a different path. Now here is the details of the method : If a queen is already placed at location (i,j) and we want to place another queen at location (k,l), then we have to check whether we can place it in that location in the following way :
1  : check j!=l (not in same column)
2  ; ((i-j)!=(k-l)) (not in same right diagonal)
3 : ((i+j)!=(k+l)) (not in same left diagonal)
The second and third condition can be combined in a single condition which is : (abs(j-l)!=abs(k-i))
--------------------------------------------------------------------------------------------------------------------------
C CODE
--------------------------------------------------------------------------------------------------------------------------
#include<stdio.h>
#include<math.h>

int x[50],soln=0;

int place(int k,int i){
//place kth queen at ith location
   int j;
   for(j=1;j<k;j++) 
//checking with previously placed queens
     if((x[j]==i) || (abs(x[j]-i)==abs(j-k)))
      return 0;
   return 1; 
//if successfully placed at ith location
}

void nqueens(int k,int n){
  int i;
  for(i=1;i<=n;i++)
    if(place(k,i)==1){ 
//if not successful then backtrack
     x[k]=i; 
//if successful then save column number
     if(k==n) 
//if all queens olaced then show solution
       display(n);
     else
       nqueens(k+1,n);
//place all other queens
    }
}

void display(int n){
   int i,j;
   soln++;
   printf("\nSOLUTION #%d\n",soln);
   for(i=1;i<=n;i++){
     for(j=1;j<=n;j++)
       if(x[i]==j)
          printf("Q\t");
       else
          printf("*\t");
     printf("\n\n");
   }
}

int main(){
   int n;
   printf("Enter no. of queens : ");
   scanf("%d",&n);
   nqueens(1,n);
   printf("TOTAL SOLN. : %d",soln);

   return 0;
}
Note : This code has been written and compiled with GCC compiler under Linux environment Ubuntu 12.04 LTS Precise Pangolin.
-------------------------------------------------------------------------------------------------------------------------
OUTPUT
------------------------------------------------------------------------------------------------------------------------- 
Enter no.of queens : 4

SOLUTION #1
*       Q       *       *

*       *       *       Q

Q       *       *       *

*       *       Q       *


SOLUTION #2
*       *       Q       *

Q       *       *       *

*       *       *       Q

*       Q       *       *
TOTAL SOLN. : 2
-------------------------------------------------------------------------------------------------------------------------
DOWNLOAD LINKS
-------------------------------------------------------------------------------------------------------------------------

Sunday 14 October 2012

Graph coloring problem with Backtracking in C

Today I am going to post a program in C that is used for solving the Graph Coloring problem.
What is Graph-Coloring : In this problem, for any given graph G we will have to color each of the vertices in G in such a way that no two adjacent vertices get the same color and the least number of colors are used.
How to solve the problem : First take input number of vertices and edges in graph G. Then input all the indexes of adjacency matrix of G whose value is 1. Now we will try to color each of the vertex. A next_color(k) function takes in index of the kth vertex which is to be colored. First we assign color1 to the kth vertex.Then we check whether it is connected to any of previous (k-1) vertices using backtracking. If connected then assign a color x[i]+1 where x[i] is the color of ith vertex that is connected with kth vertex.
--------------------------------------------------------------------------------------------------------------------------
SOURCE CODE
--------------------------------------------------------------------------------------------------------------------------
#include<stdio.h>
int G[50][50],x[50]; 
//G:adjacency matrix,x:colors
void next_color(int k){
   int i,j;
   x[k]=1; 
//coloring vertex with color1
   for(i=0;i<k;i++){
//checking all k-1 vertices-backtracking
     if(G[i][k]!=0 && x[k]==x[i])  /
/if connected and has same color
       x[k]=x[i]+1; 
//assign higher color than x[i]
   }
}

int main(){
  int n,e,i,j,k,l;
  printf("Enter no. of vertices : ");
  scanf("%d",&n); 
//total vertices
  printf("Enter no. of edges : ");
  scanf("%d",&e); 
//total edges
 
  for(i=0;i<n;i++)
    for(j=0;j<n;j++)
      G[i][j]=0; 
//assign 0 to all index of adjacency matrix
     
  printf("Enter indexes where value is 1-->\n");
  for(i=0;i<e;i++){
    scanf("%d %d",&k,&l);
    G[k][l]=1;
    G[l][k]=1;
  }
 
  for(i=0;i<n;i++)
    next_color(i); 
//coloring each vertex

  printf("Colors of vertices -->\n");
  for(i=0;i<n;i++) 
//displaying color of each vertex
    printf("Vertex[%d] : %d\n",i+1,x[i]);

  return 0;
}

NOTE : This code is written,compiled and run with GCC compiler under Linux environment Ubuntu12.04LTS Precise Pangolin.
--------------------------------------------------------------------------------------------------------------------------
OUTPUT
--------------------------------------------------------------------------------------------------------------------------
Enter no. of vertices : 4
Colored vertices of Graph G
Enter no. of edges : 5
Enter indexes where value is 1-->
0 1
1 2
1 3
2 3
3 0
Colors of vertices -->
Vertex[1] : 1
Vertex[2] : 2
Vertex[3] : 1
Vertex[4] : 3
--------------------------------------------------------------------------------------------------------------------------
RELATED POSTS
--------------------------------------------------------------------------------------------------------------------------
 To understand m-coloring i.e. to color a graph with all possible m colors (hence known as M-Way Coloring or m-coloring) visit :

Friday 17 August 2012

C program to find maximum and minimum of an array using Divide & Conquer rule

Today I am going to post a program that is going to find out the maximum and minimum element of an array. You will say that it is very easy. But here we are going to use the Divide & Conquer technique to solve this problem . This technique will be able to solve the problem in a much lesser time. Here is the code for you-

#include<stdio.h>

int a[50],max,min;

void find(int i,int n){
   int mid,max1,min1;

   if(i==n)
     max=min=a[i];
   else if(i==n-1)
     if(a[i]>=a[n-1]){
       max=a[n];
       min=a[i];
     }
     else{
       max=a[i];
       min=a[n];
     }
   else{
     mid=(i+n)/2;
     find(i,mid);
     max1=max;
     min1=min;
     find(mid+1,n);
     if(max<max1)
         max=max1;
     if(min>min1)
         min=min1;
   }


int main(){
   int i,n;

   printf("Enter size of array : ");
   scanf("%d",&n);

   printf("Enter elements in array-->\n");
   for(i=0;i<n;i++)
      scanf("%d",&a[i]);

   max=min=a[0];
   find(1,n-1);

   printf("Minimum : %d",min);
   printf("\nMaximum : %d",max);
  
   return 0;
}
NOTE : This code is compiled with GCC compiler under Linux environment Ubuntu 12.04 LTS Precise Pangolin.

Friday 27 July 2012

Important News to all followers

Over 150+ requests have come to me via email to set up a seperarte blog that deals only with java codes. So keeping in mind of all your requests I have decided to set up a new blog that will deal only with Java programs. This blog will contain posts covering most of the topics of core java and their related codes to help you out about most of the topics. So from now on you can get all related posts on my new blog at Java Code House(http://javaingrab.blogspot.com). But I will still continue posting on this blog.

Thursday 5 July 2012

Rotate Text in Java using Graphics2D

Today I will post how to continously rotate a text i.e string in Java Graphics2D. As you know that there are 4 types of transformation available in Java which are translation,rotation,scaling and shearing. Here I will use translation and rotation for this purpose. The text will be placed exactly at the center of the screen such that mid-point of text and screen coincide. Then the text will be rotated with screen center as the anchor point of rotation. Here is the code for you ->

import java.awt.*;
import java.awt.geom.*;
import java.awt.font.*;
import javax.swing.*;

public class RotateText extends JPanel{
    static int angdeg=0;
  
    @Override
    public void paint(Graphics g){
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,                         RenderingHints.VALUE_ANTIALIAS_ON);
         g2d.setColor(Color.white); //
to remove trail of painting
         g2d.fillRect(0,0,getWidth(),getHeight());
         Font font =  new Font("serif",Font.BOLD,50);
         g2d.setFont(font); 
//setting font of surface
         FontRenderContext frc = g2d.getFontRenderContext();
         TextLayout layout = new TextLayout("JAVA", font, frc);
        
//getting width & height of the text
         double sw = layout.getBounds().getWidth();
         double sh = layout.getBounds().getHeight();
        
//getting original transform instance
        AffineTransform saveTransform=g2d.getTransform();
        g2d.setColor(Color.black);
        Rectangle rect = this.getBounds();
        //
drawing the axis
        g2d.drawLine((int)(rect.width)/2,0,(int)(rect.width)/2,rect.height);
        g2d.drawLine(0,(int)(rect.height)/2,rect.width,(int)(rect.height)/2);
        AffineTransform affineTransform = new AffineTransform(); //
creating instance
       //set the translation to the mid of the component
       affineTransform.setToTranslation((rect.width)/2,(rect.height)/2);
      
//rotate with the anchor point as the mid of the text
       affineTransform.rotate(Math.toRadians(angdeg), 0, 0);
       g2d.setTransform(affineTransform);
       g2d.drawString("JAVA",(int)-sw/2,(int)sh/2);
       g2d.setTransform(saveTransform); //
restoring original transform
    }
   
    public static void main(String[] args) throws Exception{
         JFrame frame = new JFrame("Rotated text");
         RotateText rt=new RotateText();
        frame.add(rt);
        frame.setSize(500, 500);
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
      while(true){
             Thread.sleep(10);
//sleeping then increasing angle by 5
             angdeg=(angdeg>=360)?0:angdeg+5; //
             rt.repaint();
//repainting the surface
         }
    }
}

Wednesday 27 June 2012

Create your own Chat Client in Java

In my previous post I have mentioned that you cannot test the chat server code without the client code. So according to that today I will post the client code. Here also java.io and java.net packages are used for setting up the connection and for sending and receiving data. Here a Socket instance is created using the server ip adddress and port number through which it will connect to server. Then BufferedReader and PrintWriter is used for receiving and sending data. Here in the code below you will get a full GUI version of it.

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

public class ChatClient {
   
    boolean connected=false;
    Socket sock;
    BufferedReader br;
    PrintWriter pout;
   
    JFrame jf=new JFrame("ChatClient");
    JPanel
        jp1=new JPanel(),
        jp2=new JPanel(),
        mainpanel=new JPanel();
   
    JTextArea jta=new JTextArea(15,40);
    JLabel sendlabel=new JLabel("Server Text : ");
    JTextField jtf=new JTextField(20);
    JButton sendbutton=new JButton("Send");
   
    ActionListener sendlistener=new ActionListener(){
        public void actionPerformed(ActionEvent ev){
            try {
                 if(connected==true){
                     pout.println(jtf.getText());
                     jta.append("Sending : "+jtf.getText()+"\n");
                     if(jtf.getText().equals("END"))  connected=false;                    
                     jtf.setText("");
                     jtf.requestFocus();
                 }
           }catch (Exception ex) {
                 System.out.println(ex.getMessage());
           }
        }
    };

    public ChatClient() {
        try{
        buildGUI();
        }catch(Exception ex){
            System.out.println(ex.getMessage());
            }
    }
   
    public void buildGUI()throws IOException{
        jp1.setLayout(new BoxLayout(jp1,BoxLayout.X_AXIS));
        jp2.setLayout(new BoxLayout(jp2,BoxLayout.Y_AXIS));
       
        JScrollPane scroll=new JScrollPane(jta);
        scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
       
        sendbutton.addActionListener(sendlistener);
        jta.setEditable(false);
        jta.setFont(new Font("serif",Font.PLAIN,16));
       
        jp1.add(sendlabel);             jp1.add(Box.createHorizontalStrut(5));
        jp1.add(jtf);                          jp1.add(Box.createHorizontalStrut(5));        jp1.add(sendbutton);
        jp2.add(jp1);        jp2.add(Box.createVerticalStrut(10));         jp2.add(scroll);
        mainpanel.add(jp2);
       
        jf.getContentPane().add(mainpanel);
        jf.pack();
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       
        setupnetworking();
    }
   
    public void setupnetworking()throws IOException{
          InetAddress addr =InetAddress.getByName(null);
          System.out.println("addr = " + addr);
          sock =new Socket(addr, ChatServer.PORT);
// Guard everything in a try-finally to make
// sure that the socket is closed:
           try {
                System.out.println("socket = " + sock);
                connected=true;
                br =new BufferedReader(new InputStreamReader(sock.getInputStream()));
// Output is automatically flushed by PrintWriter:
               pout =new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())),true);
             
                 while(true){
                     String message="";
                     if((message=br.readLine())!="")
                         jta.append("Recieved : "+message+"\n");
                     if(connected==false)  break;
                 }
               } catch(Exception ex) {
                      System.out.println(ex.getMessage());
               }
               finally{
                     System.out.println("closing...");
                  sock.close();
               }
    }
   
    public static void main (String[] args) {
        try{
              UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
       }catch(Exception e){}
        new ChatClient();
    }
}


You can also download the source from below given link
 DOWNLOAD the source from Mediafire

Sunday 24 June 2012

Create your own Chat Server in Java

here I am going to post how you can use Java to create a Chat Server successfully. You can use Java's networking package for this purpose. Along with this you will also need java.io package for sending and receiving data to and from client. We will use ServerSocket to create a server socket at a given PORT and a Socket object that will accept a connection. After the connection is set up with client you can chat easily. Here is the code that will create a GUI based Chat Server that has a Textfield for server to write and a TextArea that contains chat contents.

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

public class ChatServer {
   
    public static final int PORT=8080; //the port that will open
    boolean connected=false;
    ServerSocket servsock;
    Socket sock;
    BufferedReader br; //for reading client data
    PrintWriter pout; //for sending server data
   
    JFrame jf=new JFrame("Server");
    JPanel
        jp1=new JPanel(),
        jp2=new JPanel(),
        mainpanel=new JPanel();
   
    JTextArea jta=new JTextArea(15,40);
    JLabel sendlabel=new JLabel("Server Text : ");
    JTextField jtf=new JTextField(20);
    JButton sendbutton=new JButton("Send");
   
    ActionListener sendlistener=new ActionListener(){
        public void actionPerformed(ActionEvent ev){
            try {
                 if(connected==true){
                     pout.println(jtf.getText()); //sending data
                     jta.append("Sending : "+jtf.getText()+"\n");
                     jtf.setText("");
                     jtf.requestFocus();
                 }
           }catch (Exception ex) {
                 System.out.println(ex.getMessage());
           }
        }
    };
   
    public ChatServer() {
        try{
           buildGUI();
        }catch(IOException ex){System.out.println(ex.getMessage());}
    }
   
    public void buildGUI()throws IOException{
        jp1.setLayout(new BoxLayout(jp1,BoxLayout.X_AXIS));
        jp2.setLayout(new BoxLayout(jp2,BoxLayout.Y_AXIS));
       
        JScrollPane scroll=new JScrollPane(jta);
        scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
       
        sendbutton.addActionListener(sendlistener);
        jta.setEditable(false);
        jta.setFont(new Font("serif",Font.PLAIN,16));
       
        jp1.add(sendlabel);             jp1.add(Box.createHorizontalStrut(5));
        jp1.add(jtf);                          jp1.add(Box.createHorizontalStrut(5));        jp1.add(sendbutton);
        jp2.add(jp1);        jp2.add(Box.createVerticalStrut(10));         jp2.add(scroll);
        mainpanel.add(jp2);
       
        jf.getContentPane().add(mainpanel);
        jf.pack();
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       
        setupnetworking();
    }
   
    public void setupnetworking()throws IOException{
            servsock = new ServerSocket(PORT);
            System.out.println("Started: " + servsock);
            try {
                  // Blocks until a connection occurs:
              sock = servsock.accept();
              try {
                System.out.println("Connection accepted: "+ sock);
                connected=true;
               
                br =new BufferedReader(new InputStreamReader(sock.getInputStream()));
                // Output is automatically flushed by PrintWriter:
                 pout =new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())),true);
                 while (true) {
                         String str = br.readLine(); //receiving data
                          if (str.equals("END")) break; /*type END to end connection. Open connection can or port can cause problem in future*/
                          if(str!="")
                          jta.append("Recieving: " +str+"\n");
                  }
                 // Always close the two sockets...
                } finally {
                   System.out.println("closing...");
                    sock.close();
                   }
                } finally {
                       servsock.close();
                        }
    }
   
    public static void main (String[] args) {
           new ChatServer();
    }
}


You can also directly download the source from below link
DOWNLOAD the source from Mediafire
NOTE : You need a Chat Client to set up the network without which you cannot test this code whether this code is working correctly or not. The Client side code will be posted very soon.

Monday 28 May 2012

Combine Multiple Shapes in Java using 2DGraphics

Constructive area geometry is a fancy name for combining shapes. Two or more shapes can be combined using different rules or operations, much the way numbers can be combined in an equation. The 2D API supports four different operations for combining the areas of two shapes:
addition (union) - The addition of two shapes is the area covered by one or both of the shapes.
intersection - The intersection of two shapes is the area that is covered by both shapes simultaneously.
subtraction - The result of subtracting one shape from another is the area covered by one that is not covered by the other.
exclusive or - The exclusive or operator is the inverse of the intersection operator. In other words, the exclusive or of two shapes is the area that is covered by one or the other of the shapes. But it does not include the area covered by both.
Shapes looking After combining
 The following interactive example, CombiningShapes, demonstrates the four area operators. It displays two shapes and a combo box that allows you to choose which area operator will be used to combine the shapes. All of this is accomplished in two methods and one constructor. The main()
method sets up a frame window to contain the example. CombiningShapes's constructor creates the two shapes and a combo box that holds the area operator names. Finally, the paint()method combines the two shapes according to the selected operator and draws the result.Screenshot of the output of code written is shown below
Screenshots of output in different cases combined together

DOWNLOAD source Java file from Mediafire
DOWNLOAD ApplicationFrame source code from Mediafire as without this program won't compile.
You can also view code from below.

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
public class CombiningShapes extends JComponent {

public static void main(String[] args) {
    ApplicationFrame f = new ApplicationFrame("CombiningShapes v1.0");
    f.add(new CombiningShapes());
    f.setSize(220, 220);
    f.center();
    f.setVisible(true);
}
private Shape mShapeOne, mShapeTwo;
private JComboBox mOptions; 


public CombiningShapes() {
   // Create the two shapes, a circle and a square.
   mShapeOne = new Ellipse2D.Double(40, 20, 80, 80);
   mShapeTwo = new Rectangle2D.Double(60, 40, 80, 80);
   setBackground(Color.white);
   setLayout(new BorderLayout());
  
   // Create a panel to hold the combo box.
   JPanel controls = new JPanel();

   // Create the combo box with the names of the area operators.
   mOptions = new JComboBox( new String[] { "outline", "add", "intersection",
        "subtract", "exclusive or" });

   // Repaint ourselves when the selection changes.
   mOptions.addItemListener(new ItemListener() {
      public void itemStateChanged(ItemEvent ie) {
       repaint();
      }
   });

   controls.add(mOptions);
   add(controls, BorderLayout.SOUTH);
}

public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D)g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
   
    // Retrieve the selection option from the combo box.
    String option = (String)mOptions.getSelectedItem();
    if (option.equals("outline")) {

       // Just draw the outlines and return.
       g2.draw(mShapeOne);
       g2.draw(mShapeTwo);
       return;
    }

    // Create Areas from the shapes.
    Area areaOne = new Area(mShapeOne);
    Area areaTwo = new Area(mShapeTwo);

    // Combine the Areas according to the selected option.
    if (option.equals("add"))
         areaOne.add(areaTwo);
    else if (option.equals("intersection"))
        areaOne.intersect(areaTwo);
    else if (option.equals("subtract"))
        areaOne.subtract(areaTwo);
    else if (option.equals("exclusive or"))
        areaOne.exclusiveOr(areaTwo);

    // Fill the resulting Area.
    g2.setPaint(Color.orange);
    g2.fill(areaOne);
    // Draw the outline of the resulting Area.
    g2.setPaint(Color.black);
    g2.draw(areaOne);
  }

Hope this helps .

Friday 25 May 2012

Draw Lines giving parabolic effect in Java

Today I am going to post a program in Java that will create an art using Java 2DGraphics and geometry. This code creates a curve like a parabola as shown in the screenshot below.
Here a set of lines are drawn with different points. The lines are drawn by joining of two points. These points are calculated very precisely over here so that whole thing gives a parabola like curve.It is very simple to create this design. Here is the code for you.

import java.awt.*;
import java.awt.geom.*;

public class Art extends Component {

     public static void main(String[] args) {
         try {
        
         ApplicationFrame f = new ApplicationFrame("ShowOff v1.0");
         f.setLayout(new BorderLayout());
         Art obj = new Art();
         f.add(obj, BorderLayout.CENTER);
         f.setSize(500,500);
         f.center();
         f.setResizable(false);
         f.setVisible(true);
      }catch (Exception e) {
           System.out.println(e);
           System.exit(0);
      }
  }
  
   private int mNumberOfLines = 25;
   private Color[] mColors = { Color.red, Color.green, Color.blue }; 

    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D)g;
        Dimension d = getSize();
        for (int i = 0; i < mNumberOfLines; i++) {
           double ratio = (double)i / (double)mNumberOfLines;
           double ratio2 = (double)(mNumberOfLines-i-1) / (double)mNumberOfLines;
           Line2D line1 = new Line2D.Double(0, ratio * d.height,
                ratio * d.width, d.height);
           Line2D line2 = new Line2D.Double(ratio*d.width,0,
                d.width, ratio*d.height);
           Line2D line3 = new Line2D.Double(d.width,ratio*d.height,
                ratio2*d.width, d.height);
           Line2D line4 = new Line2D.Double(ratio2*d.width,0,
                0, ratio*d.height);
           g2.setPaint(mColors[i % mColors.length]);
           g2.draw(line1);
           g2.draw(line2);
           g2.draw(line3);
           g2.draw(line4);
         }
    }  
}

Note : This program won't compile unless you create a Java source file named ApplicationFrame that works as a Frame object by inheriting it. So please make the necessary changes. The actual Graphics code which has given the output as shown is written in the paint(Graphics) method.

Hope this helps.

Saturday 19 May 2012

Singleton Class in Java

I hope many of you have heard of SINGLETON CLASS in Java. Even if you have not heard then also you must have experienced of such.Today I am going to post how to create a singleton class. Just as the word "single" means literally as "only one", similarly "singleton" here means "only one object". That means all classes that can have at most one object or only one object can be created of a class. You must have experienced this while installing a software. While an installation program is in progress you cannot run another installation program i.e. execute the same >EXE file while it is already in use. Here is the code for you to create a singleton class in Java -->

public final class MyClass{
    private static int count = 0;
// Optional 0
    private int n;
    public MyClass() throws Exception {
        this (0);
    }
    public MyClass(int n) throws Exception {
        if (count >= 1)
//exception object created and thrown
            throw new Exception("No more than one instance");
        count++;
        this.n = n;
    }
    public String toString() {
        return n + "";
    }
   
    public static void main(String[] args) throws Exception {
        System.out.println(new MyClass(10));
        // System.out.println(new MyClass());
       }
}

Uncomment the last line , then save it and then compile and run. It will give an output as shown below
But if it is commented then it will run absolutely fine.
Hope this helps :)

Friday 11 May 2012

Create your own Clock in Java

Many programmers would like to create a Clock of his own. Today I am going to post a code on creating a digital cum analog clock using Java. This requires some mathematical calculations to find the position of the clock hands and numbers. This is done using java's Math class API. Here is the code for you ->


import  java.util.concurrent.*;
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import java.lang.*;
import java.text.*;
import java.awt.event.*;


public class Clock extends JApplet {
    private int r;
    private boolean firsttime;
    private int x4, y4, xx4, yy4, x5, y5, xx5, yy5, x6, y6, xx6, yy6 ;
       
    private SimpleDateFormat formatter;  // Formats the date displayed
        private String todaydate,time;
        private Date currentDate;
        public void init() {
          r = 150;
          firsttime=true;
         MyThread mt = new MyThread(this);
         mt.start();
     }
   
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D)g;
       int theta, r1, r2, r3, r4,rr4,r5, rr5, r6, rr6, x1, x2, y1, y2, x3, y3 ;
       double radian;
       g2.translate(250, 250);
       if(firsttime) {
          g2.setColor(new Color(0, 0, 0));
          g2.setStroke(new BasicStroke(5));
          g2.drawOval(-r, -r, 2 * r, 2 * r);
          g2.fillOval(-r, -r, 2 * r, 2 * r);
          g2.setColor(new Color(255, 0, 0));
          g2.setStroke(new BasicStroke(2));
       
         for (theta = 0; theta < 360; theta += 6) {
            radian = theta * Math.PI / 180;
            r1 = theta % 30 != 0 ? r - 5 : r - 10;
            x1 = (int)(r1 * Math.cos(radian));
            y1 = (int)(r1 * Math.sin(radian));
            r2 = r;
            x2 = (int)(r2 * Math.cos(radian));
            y2 = (int)(r2 * Math.sin(radian));
            g2.drawLine(x1, y1, x2, y2);
        }
        g2.translate(-5, 3);
        r3 = r - 19;
        g2.setColor(new Color(84,245,245));
        ///draw number on  clock face
        for (theta = 0; theta < 360; theta += 6) {
            radian = theta * Math.PI / 180;
            if (theta % 30 == 0) {
                x3 = (int)(r3 * Math.cos(radian));
                y3 = (int)(r3 * Math.sin(radian));
                g2.drawString((theta == 270 ? 12 : (theta / 30 + 3) % 12) + "", x3, y3);
            }
        }
       
        firsttime=false;
       
        g2.translate(5, -3);   //after translation the center point is rebuild into ( 250,250 )
        }
        GregorianCalendar gc = new GregorianCalendar();
        currentDate = new Date();
        //date showing format
        formatter = new SimpleDateFormat ( "MMM dd EEE ", Locale.getDefault() );
        todaydate = formatter.format(currentDate);
        //time showing format
        formatter = new SimpleDateFormat ("hh:mm:ss ", Locale.getDefault());                      
        time=formatter.format(currentDate);
                           
        int hour = gc.get(Calendar.HOUR);
        int minute = gc.get(Calendar.MINUTE);
        int second = gc.get(Calendar.SECOND);
        int millisecond = gc.get(Calendar.MILLISECOND);
       
        //hour pointer
        radian =  (((30 * hour)+(minute/2))-90) * Math.PI / 180; 
        r4=3;
        rr4 = r-40;
        //cleanig process of previous hour pointer
        g2.setStroke(new BasicStroke(2));
        g2.setColor(new Color(0, 0, 0));
        g2.drawLine(x4,y4,xx4,yy4);
        x4=  (int)(r4 * Math.cos(radian));
        y4 = (int)(r4 * Math.sin(radian));
        xx4 = (int)(rr4 * Math.cos(radian));
        yy4 = (int)(rr4 * Math.sin(radian));
       
        //minute pointer
        radian =  (((minute*6)+(second/12))-90) * Math.PI / 180; 
        r5=9;
        rr5 = r-35;
        //cleanig process of previous minute pointer
        g2.setStroke(new BasicStroke(2));       
        g2.drawLine(x5,y5,xx5,yy5);
       
        x5=  (int)(r5 * Math.cos(radian));
        y5 = (int)(r5 * Math.sin(radian));
        xx5 = (int)(rr5 * Math.cos(radian));
        yy5 = (int)(rr5 * Math.sin(radian));
       
        //second pointer
        radian =  ((( second*6)+(millisecond/200))-90) * Math.PI / 180; 
        r6=13;
        rr6 = r-30;
        //cleanig process of previous second pointer
        g2.setStroke(new BasicStroke(2));
        g2.drawLine(x6,y6,xx6,yy6);
        x6=  (int)(r6 * Math.cos(radian));
        y6 = (int)(r6 * Math.sin(radian));
        xx6 = (int)(rr6 * Math.cos(radian));
        yy6 = (int)(rr6 * Math.sin(radian));
               
        //time showing box       
        g2.setColor(new Color(255,255,255));
        g2.fillRect(-40,50,80,20);
        g2.setColor(new Color(207,158,248));
        g2.drawRect(-40,50,80,20);
        g2.setColor(new Color(0,0,0));
        g2.drawString(time+(gc.get(Calendar.AM_PM)==1?"PM":"AM"),-35,65);
       
        //date showing box
        g2.setColor(new Color(255,255,255));
        g2.fillRect(40,-15,80,20);
        g2.setColor(new Color(207,158,248));
        g2.drawRect(40,-15,80,20);
        g2.setColor(new Color(0,0,0));
        g2.drawString(todaydate,45,0);
       
        //draw hour pointer
        g2.setColor(new Color(4,255,250));
        g2.setStroke(new BasicStroke(2));
        g2.drawOval(-3,-3,6,6);
        g2.drawLine(x4,y4,xx4,yy4);
       
        //draw minute pointer
        g2.setColor(new Color(255,0,0));
        g2.setStroke(new BasicStroke(2));
        g2.drawOval(-9,-9,18,18);
        g2.drawLine(x5,y5,xx5,yy5);
       
        //draw second pointer
        g2.setStroke(new BasicStroke(2));
        g2.setColor(new Color(11, 196, 6));
        g2.drawOval(-13,-13,26,26);
        g2.drawLine(x6,y6,xx6,yy6);
             
    }
          public static void main(String s[]) throws Exception{
         final JFrame f = new JFrame("Clock");
         final JApplet applet = new Clock();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          f.setBackground(new Color(253,206,243));
          f.setSize(500,500);
          f.setVisible(true);
          javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
            applet.repaint();   
            f.setLayout(new FlowLayout());   
            }
        });
          TimeUnit.SECONDS.sleep(0);
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
         applet.setSize(500,500);
         f.add(applet);
         applet.init();   
       }
     });
       } 
}


class MyThread extends  Thread {
    private Clock c;
    public MyThread(Clock c) {
        this.c = c;
    }
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
                c.repaint();
            }
            catch (Exception e) {
            }
       }
    }   

You can also download source from below link->
Download Java source file from Mediafire
Hope this helps .

Saturday 7 April 2012

Thread Deadlock in Java

Thread Deadlock is a special type of error that every Java programmer should try to avoid . Thread deadlock is specially related to multitasking ( i.e. Multithreaded programming ) in java . For example, suppose one thread enters the monitor on object X and another thread enters the monitor on object Y. If the thread in X tries to call any synchronized method on Y, it will be blocked . However, if the thread in Y at the same time tries to call any synchronized method on X, the thread waits forever, because to access X, it would have to release its own lock on Y so that the first thread could complete. Deadlock is a difficult error to debug.


Though in general, deadlock occurs rarely, when the two threads try to access synchronized methods defined by each other. It may involve more than two threads and two synchronized objects.


The below java code creates two classes, A and B, with methods dl1( ) and dl2( ), respectively, which pause briefly before trying to call a method in the other class. The main class, named Deadlock, creates instances of A and a B and then starts threads to set up the deadlock condition. The dl1( ) and dl2( ) methods use Thread.sleep()  as a way to force the deadlock condition to occur.



//Program to demonstrate Thread Deadlock

class A{
     synchronized void dl1(B b){
            String name=Thread.currentThread().getName();
            System.out.println(name +" entered A.");
            try{
                 Thread.sleep(1000);  // Stops the executing thread for 1000 ms
                }catch(InterruptedException e){
                        System.out.println(" A Interrupted.");
                    }
                b.last();
                System.out.println(name+"Trying to call last of B.");
       }
        public synchronized void last(){
                System.out.println("Inside A's last.");
            }
        }
class B{
        synchronized void dl2(A a){
             String name=Thread.currentThread().getName();
             System.out.println(name+" entered B");
             try{
                    Thread.sleep(1000);
             }catch(InterruptedException e){
                  System.out.println("B Interrupted.");
              }
              a.last();
              System.out.println(name+" trying to call last of A.");
            }
          public synchronized void last(){
                System.out.println("Inside B's last.");
            }
        }
public class deadlock implements Runnable{
        A a=new A();
        B b=new B();
        deadlock() {
                Thread.currentThread().setName("Main Thread.");
                Thread t=new Thread(this,"Racing Thread.");
                t.start();
                a.dl1(b);
                System.out.println("Back in Main Thread.");
            }
            public void run(){
                    b.dl2(a);
                    System.out.println("Back in other thread.");
                }
            public static void main(String args[]){
                    new deadlock();
                }
            }


P.S. : When running this code in Blu-J ( Win 7 x86 ) your system may be in the 'Stopped Responding' state. :P  Then you'll have to manually kill the process......... :)              


Hope this helps ....... :)


Tuesday 3 April 2012

Java program to handle mouse events


To handle mouse events in Java Applets , you must implement the MouseListener and the MouseMotionListener interfaces. The following applet demonstrates the process. It displays the current coordinates of the mouse in the applet’s status window.

The MouseListener interface defines mouseClicked() , mousePressed() , mouseReleased , mouseExited() and mouseEntered() methods while MouseMotionListener interface defines mouseDragged() and mouseMoved() methods. Here's the java code :
import java.awt.*;
import java.applet.*;
import java.util.*;
import java.awt.event.*;
public class MouseDemo extends Applet implements MouseListener , MouseMotionListener {
    String msg="";
    int mouseX=0,mouseY=0;
    public void init() {
        addMouseListener(this);
        addMouseMotionListener(this);
    }
     public void mouseClicked(MouseEvent me){
        mouseX=me.getX();
        mouseY=me.getY();
        msg="Mouse Clicked.";
        repaint();
      }
     public void mouseEntered(MouseEvent me){
        mouseX=0;
      mouseX=10;
        msg="Entered.";
        repaint();
     }
     public void mouseExited(MouseEvent me){
      mouseX=0;
      mouseX=10;
      msg="Exited";
        repaint();
     }
     public void mousePressed(MouseEvent me){
      mouseX=0;
        mouseY=10;
        msg="Down.";
        repaint();
     }
     public void mouseReleased(MouseEvent me){
      mouseX=me.getX();
        mouseY=me.getY();
        msg="up.";
      repaint();
     }
     public void mouseDragged(MouseEvent me){
      mouseX=me.getX();
      mouseY=me.getY();
      msg="*";
      showStatus("Dragging mouse at "+mouseX+","+mouseY);
      repaint();
      }
      public void mouseMoved(MouseEvent me){
      mouseX=me.getX();
      mouseY=me.getY();
      showStatus("Mouse is at "+mouseX+","+mouseY);
      }
    public void paint(Graphics g) {
        g.drawString(msg,mouseX,mouseY);
    }
}

After building the .class file you can embed this code in an HTML file using the below tag to run the applet in a Web Browser.

<applet source="MouseDemo" width=300 height=100>
</applet>

You can also use an in-built applet viewer ( like the one present in Blue-J ) to demonstrate the created applet .

Hope this helps :)

Sunday 1 April 2012

Java program to connect to a database Contd.

In my last post related with JDBC I mentioned only about creating tables and inserting new values to a database file using SQL statements. According to comments left by visitors today I am going to post on updating and deleting a particular record. For update or deletion of a record you will have tobe sure that the particular record actually exists in database. If this condition is not checked and you try to modify a non-existing record then you will get a run-time exception. So to avoid this first search for this record using an id(which must be unique) as below written code :
Statement stmt=con.createStatement(); //con is Connection object
ResultSet rs=stmt.executeQuery("SELECT Roll FROM Records");
//Roll is the unique id
         int an=0; 
         boolean found=false;        
         while(rs.next() && found==false){
            an=rs.getInt(0); 
//0 as Roll. is the first column
            if(an==Integer.parseInt(enter_id))  //enter_id is input id
                    found=true; 
//if id is found in database
            }

 Now you can modify or delete using id if found is true like below shown code :
if(found)  //then do anyone of below

  stmt.execute("UPDATE Records SET Sname="+n+" WHERE Roll="+enter_id); //for changing a value

  stmt.execute("DELETE Records WHERE Roll="+enter_id); //for deleting a record

Read this first -->Java program to connect to a database

Wednesday 21 March 2012

Create your own library package in Java

Today I am going to post on how you can create your own package and can import it from anywhere just like yo use import java.io.* .For this you need to do following things :
1 : Since you are thinking about package so while writing your source files write
 package <packagename> without <> . For each of your subpackages write source files in subfolders and give proper package name. e.g. creating Paint do this
     package Draw for Draw class in Draw Folder. Then create a sub folder 2DShapes containing Rectangle and Circle source codes having first line as
    package Draw.2DShapes
 2 : Next you will have to gather all your class files in a similar way as your source. To gather them all separately folder by folder use the -d command while compiling at command prompt. Type the following code
   javac -d ../classes Draw.java if you are running cmd from inside Draw folder. But remember to create classes folder in same directory as that of Draw folder.
3 : Next assemble all these classes into a JAR file without a manifest file using -cvf command.
4  ; Next open the Java folder where you have installed Java. Then look for the following folders subsequently.I mean look for
  C:\Program Files\Java\jdk1.7.0\jre\lib\ext . Inside ext folder paste your JAR file.
That's It. Now you can use your own Draw package by importing from anywhere while writing your source codes. This method is known as Java Extension Mechanism. This method is followed while developing projects using Third-Party library functions.

Tuesday 20 March 2012

Java program to connect to a database

Anyone of Java programmers have heard of JDBC. Today I am going to discuss some easiest ways of connecting to a database usin JDBC. JDBC actually stands for Java Database Connectivity. To use this technique you need JDBC drivers first of all to run the java codes. You can use Sun's JDBC-ODBC bridge by using Sun Microsystem's JDBC driver available with easysoft. But I prefer to use jstels JDBC-MDB driver(for connceting to MSAccess database files)as it does not require any installations. I will discuss my codebased on it.We wull need SQL codes to execute the Queries. You need to do the following :
1 : import java.sql.*;
2 : Create a Connection object like this ->
Class.forName("jstels.jdbc.mdb.MDBDriver2");  //loads class files of driver
Connection c=DriverManager.getConnection("jdbc:jstels:mdb:record.mdb");
3 :  Next create a Statement object like  ->
     Statement stmt=c.createStatement();
SQL Writing follow steps below ->
1 : stmt.execute("CREATE TABLE Records(Roll LONG, Sname STRING(50))"); //for creating table having the coloumns as described
2 : stmt.execute("INSERT INTO Records(Roll, Sname) VALUES(100860,'Malinga')");   //inserting values in fields

Related post and read after this --> Java program to connect to a database Contd.

Sunday 18 March 2012

Java program to list all files

This post is about a program that will be able to list all files in your computer's hard disk. This code uses java.io package for this purpose. Here I have use File class to list all the drives of your hard disk using listRoots() function. Then I have defined a recursive function that will go on till all the listings are over. The recur function takes in a File as parameter and if it is a file the it displays its absolute path and if it is a directory then again it lists all its contents and for each of its contents it calls the recur function recursively. Here is the code for you :
import java.io.*;
public class FileList {

    static void recur(File f1){
        if (f1.isFile()){
            System.out.println(f1.getAbsolutePath()); //displays path for a file
            return;
        }
        else{
            File f[]=f1.listFiles();  //lists all contents if a directory
            for (int j = 0; j<f.length; j++)
                try{
                recur(f[j]);  //calls recur for each content of directory
                }catch(Exception e){e.printStackTrace();}
        }
    }
   
    public static void main(String[] args){
        File []A=File.listRoots();  //lists all drives
           try{
               for(int i=0;i<A.length;i++)
                recur(A[i]);  //calls recur for each drive
            }catch(Exception e){e.printStackTrace();}       
    }
}

Sunday 11 March 2012

Best News

I have just done a rocking performance. I think that it is the biggest achievement in my life so far. I suggested some things to a Nokia S40 phone app which has given it a new look. For this performance I was asked to accomplish the job but due to lack of time I couldn't complete it. But for my recommendation Nokia has given me a software for easy creation of Nokia and Windows phone app. Besides this from now on I can advertise my apps on Windows Marketplace and Nokia Store and can also monetise my apps.

Friday 2 March 2012

Remove Recycle Bin from Desktop

In this post I will show you a trick to remove recycle Bin from desktop of Windows7. This is for all those who do not like the Recycle Bin on their Desktop.

1 : Go to Start>Run. Type gpedit.msc
2 : On the left panel under User Configuration expand the tree Administrative templates

3 : Click on the subtree Desktop. Do not expand it
4 : On the right panel select Remove Recycle Bin icon from desktop properties.
5 : Double click the option, on settings tab select the option enabled, press OK and exit the window.
6 : Refresh the desktop, Recycle Bin vanishes. If not then logout and re-login.

Monday 27 February 2012

A note to all my blog visitors

I would like to inform all my blog visitors that I have resolved the problem which I was facing earlier. Now I am able to access my4shared account. I have also So all of you can get the full codes from now on besides the important functions. I will include the important functions in my posts as suggested by certain visitors so that you can understand the codes even without downloading them as it is not possible to post codes of more than 100 lines like that of GUI programs.

Sunday 19 February 2012

Change Logon Screen Background of Windows7

Everyone would like to change the logon screen backgroundof Windows7. This will give your Windows7 a customized look. You can set your own picture as background svreen. You will have to follow the steps below to change background screen -->
1 : The image that you should set should be a .jpg file and its size should be less than 245KB.
2 : The image can have any resolution. I personally have used 1400 x 900. This is actually my screen resolution. You can use any photo editors to change resolutions. But you will have to save the image with file name backgroundDefault.jpg.
3 : Next you will have to copy the image to
C:\Windows\system32\oobe\info\backgrounds
If this path does not exist then you will have to create it.
4 : Go to Run and type regedit. This will open Registry Editor. Navigate to
HKLM\Software\Microsoft\Windows\CurrentVersion\Authentication\
LogonUI\Background


If background does not exist then right-click LogonUI, select New and then Key and name it Background. Now locate OEMBackground in the right pane. If it does not exist, then right-click Background and select New and then DWORD and name it OEMBackground.
5 : Double click on OEMBackground and set the Value Data to 1.
6 : Log off to see the new logon screen. In order to go back to old background screen set Value Data to 0.

Apology to all my blog visitors

Here I would like to apologize for problems that you might have faced these days while viewing my blog. I would like to inform you that for certain reasons I am unable to upload files to my 4shared account. I am also not able to give links to certain programs that I have written and have posted in my blog. So in this regard I want that you people will give me some time in finding out the problem in order to provide you with latest posts and programs. Hence you people may not be able to get certain programs now. Therefore from now on I will try to post only certain functions rather than full codes to help you out till the problem is solved.

Saturday 18 February 2012

C program Virus to disable USB ports

C programming language is very useful in gaining access to system softwares and information. Keeping this view in mind or rather to say using this ability of C language I have created a virus program which is able to gain access to registry and disable USB ports. Here I have used the system function to disable USB ports.

The C code to block USB ports -->
#include<stdio.h>
void main(){
          system("reg add HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\USBSTOR \/v Start \/t REG_DWORD \/d 4 \/f");
}

The C code to unblock USB ports -->
#include<stdio.h>
void main(){
          system("reg add HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\USBSTOR \/v Start \/t REG_DWORD \/d 3 \/f");
}

Thursday 16 February 2012

Java program to compress a file using GZIP

Java can be very efficiently used in compressing files. Java's util package contains certain library classes known as GZIPOutputStream which can be used to compress a file with file extension as .gz. Again we can use GZIPInputStream to decompress any file with extension .gz. Here I will post a function that takes in source and destination file as parameter. It then reads source using FileInputStream and writes the output to destination using GZIPOutputStream. A buffer array is taken which reads certain bytes at a time from source.
Function written below :
     public void gzipFile(String src, String dest) throws Exception {
            FileInputStream in = new FileInputStream(src);
            GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(dest));
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1)
                 out.write(buffer, 0, bytesRead);
            in.close();
            out.close();
     }

Monday 6 February 2012

Windows7 usage without Activation for one year

Most of you might be aware of the fact that it is possible to use Windows 7 and Vista for 120 days without activation. This is possible using the slmgr -rearm command which will extend the trial period from 30 days to 120 days. However in this post I will show you a trick by which it is possible to use Windows 7 without activation for an year.

1 : Goto Start Menu>Run. Type cmd and press Enter.

2 : Now type slmgr -rearm and hit enter at prompt.

3 : You will be prompted to restart the computer. Once restarted the trial period will be once again reset to 30 days. You can  use above command for up to 3 times by which you can extend the trial period to 120 days without activation.

4 : Now comes the actual trick by which you can extend the trial period from 120 days to 360 days. Open Registry Editor (type regedit in Run and hit Enter) and navigate to the following location
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SoftwareProtectionPlatform

5 : In right-side pane, change value of SkipRearm to 1.

6 : Now you will be able to use the slmgr -rearm command for another 8 times so that you can skip activation process for another 240 days. So you will get 120 + 240 = 360 days of free Windows 7 usage.