Skip to main content

Posts

Showing posts from 2012

Implement Button Click (ActionEvent) using swing and applet

Following example is to demonstrate button click event using actionListener and ActionEvent in java  import java.awt.*; import java.applet.*; import java.awt.event.*; /* <Applet code=buttonclick width=300 height=300> </Applet> */ public class buttonclick extends Applet implements ActionListener { TextField text1;    Button button1;    Label l1;      public void init()    { l1=new Label("Message: ");       add(l1);       text1=new TextField(15);       add(text1);       button1=new Button("Click");       add(button1);       button1.addActionListener(this);    }     public void actionPerformed(ActionEvent e1)    { String str="Hello, java is Great";       if(e1.getSource()==button1)        text1.setText(str);    } } To compile this program: Goto command prompt type "javac buttonclick.java" To execute this program: Type "appletviewer buttonclick.java"

Mid Point Circle Algorithm Implementation in C

#include<graphics.h> #include<stdio.h> #include<conio.h> #include<dos.h> void main() {  int i,x,y,r,p,midx,midy;  int gd=DETECT,gm,xcenter,ycenter;  printf("Enter the radius  :");  scanf("%d",&r);  initgraph(&gd,&gm,"..\\bgi");  midx=getmaxx()/2;  midy=getmaxy()/2;  xcenter=midx;  ycenter=midy;  x=0;  y=r;  p=1-r;  midpoint(xcenter,ycenter,x,y,p); // to draw circle  //to draw asterik (2 horizontal n vertical lines)  //inside the circle.  for(i=0;i<=r;i++)  { putpixel(xcenter+i,ycenter,10);    putpixel(xcenter-i,ycenter,10);    putpixel(xcenter,ycenter+i,10);    putpixel(xcenter,ycenter-i,10);  }  getch();  closegraph(); }  midpoint(int xcenter,int ycenter,int x,int y,int p)  {  while(x < y)  {  plotcircle(xcenter,ycenter,x,y);  if(p<0)  p=p+2*x+1;  else  {  p=p+2*(x-y)+1;  y=y-1;  }  x=x+1;  }  if(x==y)  plotcircle(xcenter,ycenter,x,y);  return;  }  plotcircle(int xcenter,int ycenter,int x,int y)  {  putp

Bresenham Circle Algorithm Implementation in C

# include<stdio.h> # include<conio.h> # include<graphics.h> void main() {  int gd=DETECT,gm;  int r,x,y,p,xc=320,yc=240,i;  initgraph(&gd,&gm,"..\\BGI");  printf("Enter the radius ");  scanf("%d",&r);  for(i=0;i<10;i++);  {  x=0;  y=r;  //putpixel(xc+x,yc-y,15);  p=3-(2*r);  for(x=0;x<=y;x++)  {  if (p<0)  {   y=y;   p=(p+(4*x)+6);  }  else  {   y=y-1;   p=p+((4*(x-y)+10));  }  putpixel(xc+x,yc-y,15);  putpixel(xc-x,yc-y,15);  putpixel(xc+x,yc+y,15);  putpixel(xc-x,yc+y,15);  putpixel(xc+y,yc-x,15);  putpixel(xc-y,yc-x,15);  putpixel(xc+y,yc+x,15);  putpixel(xc-y,yc+x,15);  }  r=r-10;  //xc=xc-5;  //yc=yc-5;  }  getch();  closegraph(); }

Cohen Sutherland Line Clipping in C++

#include<iostream> using namespace std; #include "graphics.h" #define INSIDE 0 #define LEFT 1 #define RIGHT 2 #define BOTTOM 4 #define TOP 8 int code(int x,int y,int xmin,int ymin,int xmax,int ymax) { int outcode; if(x<xmin) outcode=LEFT; else if(x>xmax) outcode=RIGHT; else if(y<ymin) outcode=BOTTOM; else if(y>xmax) outcode=TOP; else outcode=INSIDE; return outcode; } void clip(int x1,int y1,int x2,int y2,int xmin,int ymin,int xmax,int ymax) { int outcode1=code(x1,y1,xmin,ymin,xmax,ymax); int outcode2=code(x2,y2,xmin,ymin,xmax,ymax); bool accept=false; while(true) { if(!(outcode1 | outcode2)) { accept=true; break; } else if(outcode1 & outcode2) break; else { int x,y; int outcodeout=outcode1?outcode1:outcode2; if(outcodeout & TOP) { x=x1+(x2-x1)*(ymax-y1)/(y2-y1); y=ymax; } else if(outcodeout & BOTTOM) { x=x1+(x2-x1)*(ymin-y1)/(y2-y1); y=ymin; } else if

Invoking main method from another class in java

public class test1 {         static int count; public static void main(String args[]) { System.out.println("Inside test1 class"); if(count<=1) { count++;        test2 obj = new test2();  } } } class test2 { public test2() { String args[] = new String[] {"ABC"}; System.out.println(" Inside test2 class\n Now, invoking main method of test1 class"); test1.main(args); } }                                                                     Next >>  Error: main methods starts with capital M in java

Error: main method's m starts with capital letter

Code:- public class test1 { public static void Main(String args[]) // here  main method starts with capital letter (like Main) { System.out.println("Testing Main Method"); } } This program will compile but does not run. IT give a runtime error: "main method not found in test1 class" Solution: change the capital m to small case letter (main).

Invoking main Method in java program

main Method placed in another class rather than the program's starting class Suppose I create a java program named as Test1.java . In this I added two classes Test1 and Test2. If I place main method in Test2 class then it will give a runtime error like "main method not found in test1 class". For Example: - class test1 { public static void display() { System.out.println("Inside Test1 Class"); } } class test2 { public static void main(String args[]) { System.out.println("Inside Test2 class"); test1.display(); } }   Solution: Save the above program with test2.java then compile and run.                                                                              Next >>  Invoking main method from another class

Multiple main methods in a Java Program

Main method is the only entry point of the java console application. Normally we used only one main method in our program. A java application can have multiple main methods. Code: -  // myclass.java class test { public static void main(String args[]) { System.out.println("Main of test class..."); } } public class Myclass { public static void main(String args[]) { String str[]={"A","B","C"}; test.main(str); } }  In the above example, program starts from Myclass . For invoking a  main method it require a command line arguments also. So that we declared and initialized str[] and passed it to the test.main(str);

Java.lang.NoClassDefFoundError problem Solved

Exception in thread "main" java.lang.NoClassDefFoundError Sometimes when we try to execute java program we got error message like "Exception in thread "main" java.lang.NoClassDefFoundError". But this is not a major issue. It just a common human mistake. You might have compiled java program with small letter-case followed by .java extension but actually file name is in the capital letters. The program will compile without any error but do not. Note: Check filename before you compile java program ( Java is case Sensitive). for example: In my case: filename is MyClass.java I compiled it as javac myClass.java        Compiled successfully But do not execute... give error message like this Solution: Compile it as javac Myclass.java Java is very case sensitive language.

Use of setPriority method of Thread Class in java

import java.io.*; class A extends Thread { public void run()    { System.out.println("Thread A started");       for(int i=5;i>0;i--)       { System.out.println(i);        }     } } class B extends Thread { public void run()    { System.out.println("Thread B started");       for(int i=5;i>0;i--)       { System.out.println(i);       }     } } class C extends Thread { public void run()    { System.out.println("Thread C started");       for(int i=5;i>0;i--)       { System.out.println(i); }     } } class thread3 { public static void main(String args[])    { A thread_a=new A();       B thread_b=new B();       C thread_c=new C();       thread_c.setPriority(Thread.MAX_PRIORITY);       thread_b.setPriority(thread_a.MAX_PRIORITY);       thread_a.setPriority(Thread.MIN_PRIORITY);       System.out.println("Thread A");       thread_a.start();       System.out.println("Thread B");       thread_b.st

Implementation of all methods of the String class in java

import java.io.*; class strclass { public static void main(String args[])throws IOException    { String str,s2;       int ch,pos;       DataInputStream in=new DataInputStream(System.in);       while(true)       {       System.out.println("\n-------STRING CLASS--------\n");       System.out.print("\n 1. To Upper Case");       System.out.print("\n 2. To Lower Case");       System.out.print("\n 3. Replace");       System.out.print("\n 4. Trim");       System.out.print("\n 5. Equals");       System.out.print("\n 6. Equals Ignore Case");       System.out.print("\n 7. Length");       System.out.print("\n 8. Char At");       System.out.print("\n 9. Compare To");       System.out.print("\n 10. Concatenate");       System.out.print("\n 11. Substring");       System.out.print("\n 12. IndexOf");       System.out.print("\n 0. EXIT");  

Implementation of all methods of the vector class in java

import java.io.*; import java.util.*; class vecmethod { public static void main(String args[])throws IOException    { String s1,s2;       int ch,size,pos;       Vector list=new Vector();       DataInputStream in=new DataInputStream(System.in); System.out.print("\n\n Enter no. of Items: ");                     size=Integer.parseInt(in.readLine()); String s[]=new String[size];       while(true)       {       System.out.println("\n-------VECTOR CLASS--------\n");       System.out.print("\n 1. Add Element");       System.out.print("\n 2. Element At");       System.out.print("\n 3. Size");       System.out.print("\n 4. Remove Element(Item)");       System.out.print("\n 5. Remove Element(Pos) ");       System.out.print("\n 6. Remove All Element");       System.out.print("\n 7. Copy Into(array)");       System.out.print("\n 8. Insert Element");       System.out.print(&q

Generate series of prime numbers using java

import java.io.*; class prime_series {    public static void main(String args[])   { int st,end;     int flag=0;     DataInputStream in=new DataInputStream(System.in);     System.out.print("Enter starting range: ");     st=Integer.parseInt(in.readLine());     System.out.print("\nEnter ending range: ");     end=Integer.parseInt(in.readLine());     for(int i=st;i<=end;i++)     {      for(int j=2;j<=i/2;j++)      { if(i%j==0)         { flag=1;            break;          }        else         flag=0;      }      if(flag==0)       System.out.print(i + " ");     }   } }    

C++ program to implement scaling w.r.t origin

#include"graphics.h" #include<iostream> using namespace std; int main() { int count=0,y,factor[3][3],sx,sy; cout<<"Enter No. of cordinates: "; cin>>y; int **matrix, **m2; matrix=new int*[3]; m2=new int*[3]; for(int i=0;i<y;i++) { matrix[i]=new int[y]; m2[i]=new int[y]; } //initailization for(int i=0;i<y;i++) { for(int j=0;j<3;j++) { if(j==1) { cout<<"\n\nEnter y-axis value for cordinate-"<<i+1<<" = "; cin>>matrix[j][i]; } else if(j==2) matrix[j][i]=1; else { cout<<"\n\nEnter x-axis value for cordinate-"<<i+1<<" = "; cin>>matrix[j][i]; } } } cout<<"\n\nEnter scaling factor for x: "; cin>>sx; cout<<"\n\nEnter scaling factor for y: "; cin>>sy; for(int i=0;i<3;i++) { for(int j=0;j<y;j++)

C++ program to implement Translation w.r.t origin

#include"graphics.h" #include<iostream> using namespace std; int main() { int count=0,y,factor[3][3],tx,ty; cout<<"Enter No. of cordinates: "; cin>>y; int **matrix, **m2; matrix=new int*[3]; m2=new int*[3]; for(int i=0;i<y;i++) { matrix[i]=new int[y]; m2[i]=new int[y]; } //initailization for(int i=0;i<y;i++) { for(int j=0;j<3;j++) { if(j==1) { cout<<"\n\nEnter y-axis value for cordinate-"<<i+1<<" = "; cin>>matrix[j][i]; } else if(j==2) matrix[j][i]=1; else { cout<<"\n\nEnter x-axis value for cordinate-"<<i+1<<" = "; cin>>matrix[j][i]; } } } cout<<"\n\nEnter translation factor for x: "; cin>>tx; cout<<"\n\nEnter translation factor for y: "; cin>>ty; for(int i=0;i<3;i++) { for(int j=0;j<y;

Program to implement Thread by extending Thread class in java

import java.io.*; class NewThread extends Thread { NewThread()   { super("Demo Thread");      System.out.println("child thread: "+this);      start();    }    public void run()    { try       { for(int i=5;i>0;i--)          { System.out.println("child thread: " + i);             Thread.sleep(500);           }        }catch(Exception e){}       System.out.println("Exiting child thread");     }  }     class thread2     { public static void main(String args[])       { NewThread obj=new NewThread();          try          { for(int i=5;i>0;i--)             { System.out.println(" Main thread: " +i);                Thread.sleep(1000);              }           }catch(Exception e){}           System.out.println("Exiting Main Thread");        }       }    

Java program to count objects using static variable

import java.io.*; class obj_call { static int count;      obj_call()    { count++;    } } public class count_obj { public static void main(String args[])    { obj_call e1= new obj_call();       System.out.println("\n Hi, Welcome to Java programming");       obj_call e2= new obj_call();       System.out.println("\n Java is fully OOP's language");       obj_call e3= new obj_call();       System.out.println("\n It provide more security than the c++");       System.out.println("\n No. of objects : "+ obj_call.count);    } }

C program to implement bresenham's line drawing algorithm

#include<graphics.h> #include<conio.h> #include<math.h> void bress(float x1,float y1,float x2,float y2)  { int x,y,end,inc=0,p,dx=abs(x2-x1),dy=abs(y2-y1),c=0,current=0; if(dx>dy) { p=2*dy-dx; if(x1<x2) { x=x1;y=y1;end=x2; if(y1<y2)inc=1; if(y1>y2)inc=-1; } else { x=x2;y=y2;end=x1; if(y2<y1)inc=1; if(y2>y1)inc=-1; } while(x<=end) { putpixel(x,y,15); if(p<0) p=p+2*dy; else { y=y+inc;p=p+2*(dy-dx); } x++; } } else { p=2*dx-dy; if(y1<y2) { y=y1;x=x1;end=y2; if(x1<x2)inc=1; if(x1>x2)inc=-1; } else { y=y2;x=x2;end=y1; if(x2<x1)inc=1; if(x2>x1)inc=-1; } while(y<=end) { putpixel(x,y,15); if(p<0)p=p+2*dx; else { x=x+inc;p=p+2*(dx-dy); } y++; if(current==0&&c==10) { current=1;c=-1; } if(current==1&&c==6) { current=0;c=-1; } c++; } }  } void main() { int g

C program to implement DDA algorithm

#include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> #define round(a) ((int) (a+0.5)) void lineDDA(int xa,int ya,int xb,int yb); int main(void) {    /* request auto detection */    int gdriver = DETECT, gmode, errorcode;    int xa,ya,xb,yb;    /* initialize graphics and local variables */    initgraph(&gdriver, &gmode, "..\\bgi");    lineDDA(0,0,640,480);    lineDDA(640,0,0,480);    lineDDA(320,0,320,480);    lineDDA(0,240,640,240);    getch();    closegraph();   } void lineDDA(int xa,int ya,int xb,int yb) { int dx=xb-xa,dy=yb-ya,steps,k; float xinc,yinc,x=xa,y=ya; if(abs(dx)>abs(dy)) steps=abs(dx); else steps=abs(dy); xinc=dx/(float) steps; yinc=dy/(float) steps; putpixel(round(x),round(y),5); for(k=0;k<steps;k++) {       x+=xinc; y+=yinc; putpixel(round(x),round(y),2); } }

C++ program to show simple animation in Visual Studio 2008

#include "graphics.h" int main( ) {     initwindow(1000, 700, "Animation");   for(int i=0;i<47;i++) //for +x-axis { line(500,0,500,1000); line(0,350,1000,350); circle(530+(i*10),320,30); delay(100); clearviewport(); } for(int i=0;i<47;i++) //for -x-axis { line(500,0,500,1000); line(0,350,1000,350); circle(0+(i*10),320,30); delay(100); clearviewport(); } for(int i=0;i<32;i++) //for +y-axis { line(500,0,500,1000); line(0,350,1000,350); circle(470,320-(i*10),30); delay(100); clearviewport(); } for(int i=0;i<32;i++) //for -y-axis { line(500,0,500,1000); line(0,350,1000,350); circle(470,700-(i*10),30); delay(100); clearviewport(); } while(!kbhit()) { outtextxy(500,350,"Press any key to exit..."); delay(100); }     return 0; }

Java program to calculate BMI (Body Mass Index)

import java.util.Scanner; public class BMI_Calc {         public static void main(String args[])         {                 double wt, ht,bmi;                 Scanner sc=new Scanner(System.in);                 System.out.print("Enter your wieght in pounds: ");                 wt=sc.nextDouble();                 System.out.print("\nEnter your hieght in inches: ");                 ht=sc.nextDouble();                 wt=wt*0.45359237;                 ht=ht*0.0254;                 bmi=wt/(ht*ht);                 System.out.print("\n\nBMI = " + bmi);         } }

Java program to display formatted output

Suppose the tuition for a university is $5,000 this year and increases 4.5% every year. Write a program that displays the tuition for the next four years. Display two digits after the decimal point. public class Q1 {         public static void main(String args[])         {                 double fee=5000;                 for(int i=0;i<4;i++)                 {                         fee=(fee*0.045) + fee;                         System.out.format("Increased fee for %d year = $%6.2f%n",(i+1),fee);                 }         } }

Java program To read a string and change it to alphabetical order. eg STRING=GINRST

import java.io.*; class charsort { public static void main(String args[])throws IOException    { String s1;       char temp;           DataInputStream in=new DataInputStream(System.in);       System.out.print("\n\n Enter string:  ");       s1=in.readLine();       char z[]=new char[s1.length()];       z[0]+=s1.charAt(0);       for(int i=1;i<s1.length();i++)       { z[i]+=s1.charAt(i);                    for(int j=0;j<=i;j++)          { for(int k=j+1;k<=i;k++)            { if(z[j]>z[k])               { temp=z[k];                  z[k]=z[j];                  z[j]=temp;               }             }           }         }        System.out.print("\n\n Sorted string is:  ");        for(int m=0;m<s1.length();m++)        System.out.print(z[m]); } }      

Java program to find perfect integers

import java.util.Scanner; public class PerfectIntegers {         public static void main(String args[])         {                 int num,sum=0,count=2,p_count=0;                 Scanner sc=new Scanner(System.in);                 System.out.println("First four Perfect Integers are:");                 while(true)                 {                               for(int i=1;i<=count/2;i++)                         {                                 if(count%i==0)                                         sum+=i;                         }                         if(sum==count)                         {                                 System.out.print(" " + count);                                 p_count++;                         }                         sum=0;                         count++;                                               if(p_count==4)                                 break;                 }                 System.out.pr

How to Install and Run PHP file

To download wampserver and it's installation, and  To run php script on browser Step 1: Download php Virtual server like WAMPSERVER or XAMPP http://www.wampserver.com/ Note: - Download php and VC10 (link is provided in warning section) Step 2: After that, install php. (Follow the steps and just click next...next...next...). Step 3: After the complete installation, start wampserver. Step 4: Now go to System tray and click on wampserver icon. Step 5: Click on “start all Services” (Now icon turns green) Note: - If the icon turns green that means all services are started or red then services are stopped or yellow that means temporarily stopped (you need to start all services). Step 6: Now click on “www directory” Step 7: Create new folder (in my case, named it as “vik”). Step 8: Open vik folder and create php file e.g.: Type the below php script in notepad or any other text editor as you want (It is bet