You are on page 1of 87

1

LIST OF EXPERIMENTS
S.NO
EX.
NO
NAME OF THE EXPERIMENTS PAGE NO
1
2
3
4
5
6
7
8
9
10
11
12
2
Ex.No.1 JAVA DOC COMMENTS
AIM
To develop a Java package with simple Stack and Queue classes. Use JavaDoc
comments for documentation.
ALGORITHM
(i) Start
(ii) Constructthequeue
(iii) If theQueueislogicallyemptyreturntrueelsereturnfalse
(iv) Usingenqueuemethod,thenewitemcanbeinsertedintothequeue.
(v) Usingdequeuemethod,theleast recentlyinserteditemscanberemoved.
(vi) Stop
arrayqueue.java
package qstack;
/**
* Array-based implementation of Queue
* @author Xyz
*/
public class arrayqueue {
private Object[] thearray;
private int currentsize;
private int front;
private int back;
private static final int DEFAULT_CAPACITY=10;
/**
* consruct the queue
*/
public arrayqueue()
{
thearray=newObject[DEFAULT_CAPACITY ];
3
makeEmpty();
}
/**Test if the queue is logically empty
* @return <b> true</b> if empty <code> false</code> otherwise
*/
public boolean isempty()
{
return currentsize==0;
}
/**
* make the queue logically empty
*/
public void makeEmpty()
{
currentsize=0;
front=0;
back=-1;
}
/**Return & Remove the least recently inserted item
* @return the least recently inserted
* item in the queue
*/
public Object dequeue()
{
if(isempty())
thrownewRuntimeException(" Array Queue Deque ");
currentsize--;
Object returnvalue=thearray[front];
front=increment(front);
4
return returnvalue;
}
/**
*Get the least recently inserted item in the queue
*not return the queue
*@return the least recenly inserted item in the queue
*/
public Object getfront()
{
if(isempty())
{
thrownewRuntimeException("Array queue get front");
}
return thearray[front];
}
/**
* insert a new item into the queue
* @param
* the item to insert
*/
public void enqueue(Object x)
{
if(currentsize==thearray.length)
doublequeue();
back=increment(back);
thearray[back]=x;
currentsize++;
}
/**
* internal method to increment with wrapround
* @param x any index in the array is range
5
* @return x+1 or 0 if x is at the end of the array
*/
private int increment(int x)
{
if(++x==thearray.length)
x=0;
return x;
}
/**
* internal method to expand */
private void doublequeue()
{
Object[] newarray;
newarray= newObject[thearray.length*2];
//copy the elements that are logically in the queue
for(int i=0;i<currentsize;i++,front=increment(front))
{
newarray[i]=thearray[front];
front=0;
back=currentsize-1;
}}}
arraystack.stack
package qstack;
/**
* Array Based implementation of Stack
* @author Xyz
*/
public class arraystack {
private Object[] thearray;
private int topofstack;
6
private static final int DEFAULT_CAPACITY=10;
/**
* construct the stack
*/
public arraystack()
{
thearray= newObject[DEFAULT_CAPACITY];
topofstack=-1;
}
/**
* test if the stack is logically empty
* @return true if empty,false otherwise
*/
public boolean isempty()
{
return topofstack==-1;
}
/**
* Make the stack logically empty
*/
public void makeempty()
{
topofstack=-1;
}
/**
* get the most recently inserted element
*/
public Object top()
{
if(isempty())
thrownewRuntimeException("Array stack top");
7
return thearray[topofstack];
}
/**
* remove the most recently inserted item
*/
public void pop(){
if(isempty())
thrownewRuntimeException("Array stack pop");
topofstack--;
}
/**
* return and remove the most recently inserted item from stack
* @return the most recently inserted item in the stack
*/
public Object topandpop()
{
if(isempty())
thrownewRuntimeException("Array Stack top & pop");
return thearray[topofstack--];
}
/**
* insert a new item into the stack
* @param x the item to insert
*/
public void push(Object x)
{
if(topofstack+1==thearray.length)
doublearray();
thearray[++topofstack]=x;
}
/**
* Internal method to extend the array
*/
private void doublearray()
{
Object[] newarray;
8
newarray=newObject[thearray.length*2];
for(int i=0;i<thearray.length;i++)
newarray[i]=thearray[i];
thearray=newarray;
}}
queuestacktester.java
package qstack;
public class queuestacktester {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Queue Example");
arrayqueue aq=newarrayqueue();
aq.enqueue(newString("1"));
aq.enqueue(newString("2"));
aq.enqueue(newString("3"));
aq.enqueue(newString("4"));
System.out.println("Queue->1,2,3,4");
System.out.println("queue->"+ aq.getfront());
System.out.println("Queue Removed element->"+aq.dequeue());
System.out.println("Queue FIFO->"+aq.getfront());
System.out.println("stack eg");
arraystack as=new arraystack();
as.push(new String("a"));
as.push(new String("b"));
as.push(new String("c"));
as.push(new String("d"));
System.out.println("Stack LIFO->"+as.top());
as.pop();
System.out.println("Pop on stack");
System.out.println("Stack LIFO ->"+as.top());
}}
9
OUTPUT:
Queue Example
Queue->1,2,3,4
queue->1
Queue Removed element->1
Queue FIFO->2
stack eg
Stack LIFO->d
Pop on stack
Stack LIFO ->c
10
Ex.No.2 COMPLEX NUMBERS
AIM
To design a class for Complex numbers in Java. In addition to methods for basic
operations on complex numbers, provide a method to return the number of active objects
created.
ALGORITHM
(i) Start
(ii) Createdefault constructor
(iii) Create one parameterized constructor and we used this () which is used point the
current object
(iv) Create a object for all classes, such as complex addition, division , multiplication ,
subtraction.
(v) Stop
PROGRAM:
Complexnumber.java
package compno;
public class complexnumber {
public static int counter=0;
private double realpart;
private double imaginarypart;
/**
* default constructor
*/
public complexnumber()
{
counter++;
}
/**
* parametrized constructor
* @param realpart
* @param imaginarypart
*/
public complexnumber(double realpart,double imagpart)
{
this();
this.realpart=realpart;
this.imaginarypart=imagpart;
}
11
public complexnumber(complexnumber comnum)
{
this();
this.realpart=comnum.getrealpart();
this.imaginarypart=comnum.getimagpart();
}
public double getrealpart()
{
return realpart;
}
public void getrealpart(double realpart)
{
this.realpart=realpart;
}
public double getimagpart()
{
return imaginarypart;
}
public void getimagpart(double imagpart)
{
this.imaginarypart=imagpart;
}
public complexnumber getcomplexconjugate()
{
return newcomplexnumber(this.realpart,this.imaginarypart*-1);
}
public complexnumber multiplyto(complexnumber multicomnum)
{
complexnumber result=new complexnumber();
//(a+bi)(c+di)=ac+adi-bd+bdi
double _real=((this.realpart*multicomnum.getrealpart())-
(this.imaginarypart*multicomnum.getimagpart()));
double
_imag=((this.realpart*multicomnum.getimagpart())+(this.imaginarypart*multicomnum.g
etrealpart()));
result.getrealpart(_real);
result.getimagpart(_imag);
return result;
}
/**
* @param sub comnum
* @return
*/
public complexnumber subto(complexnumber subcomnum)
{
12
complexnumber result=new complexnumber();
//(a+bi)-(c+di)=(a-c)+(b-d)i
double real=(this.realpart-subcomnum.getrealpart());
double imag=(this.imaginarypart-subcomnum.getimagpart());
result.getrealpart(real);
result.getimagpart(imag);
return result;
}
/**
* @param add comnum
* @return
*/
public complexnumber addto(complexnumber addcomnum)
{
complexnumber result=new complexnumber();
//
double real=(this.realpart+addcomnum.getrealpart());
double imag=(this.imaginarypart+addcomnum.getimagpart());
result.getrealpart(real);
result.getimagpart(imag);
return result;
}
/**
* @param div1 com num
* @return
*/
public complexnumber divto(complexnumber divcomnum)
{
complexnumber result=new complexnumber(divcomnum);
//(a+bi)/(c+di)=((ac+bd)+(bc-ad)i)/(c2-d2)
result=this.multiplyto(divcomnum.getcomplexconjugate());
double
dnr=divcomnum.getrealpart()*divcomnum.getrealpart()+divcomnum.getimagpart()*divco
mnum.getimagpart();
result.getrealpart(result.getrealpart()/dnr);
result.getimagpart(result.getimagpart()/dnr);
return result;
}
public String toString()
{
String
imgpart=((this.imaginarypart)<0?String.valueOf (this.imaginarypart):"+"+this.imaginary
part);
return this.realpart+imgpart+"i";
}
public static void main(String[] args){
System.out.println("Complex number example");
13
complexnumber cn=newcomplexnumber(8,4);
complexnumber cn2=newcomplexnumber(1,2);
System.out.println("complexnumber="+cn);
System.out.println(cn+"complex conjugate="+cn.getcomplexconjugate());
System.out.println("\nComplex multiplication");
System.out.println("("+cn+")("+cn2+")="+cn.multiplyto(cn2));
System.out.println("\nComplex addition");
System.out.println("("+cn+")+("+cn2+")="+cn.addto(cn2));
System.out.println("\nComplex division");
System.out.println("("+cn+")/("+cn2+")="+cn.divto(cn2));
System.out.println("\nComplex subtraction");
System.out.println("("+cn+")-("+cn2+")="+cn.subto(cn2));
System.out.println("Number of active objects created="+counter);
} }
OUTPUT:
Complex number example
complexnumber=8.0+4.0i
8.0+4.0icomplex conjugate=8.0-4.0i
Complex multiplication
(8.0+4.0i)(1.0+2.0i)=0.0+20.0i
Complex addition
(8.0+4.0i)+(1.0+2.0i)=9.0+6.0i
Complex division
(8.0+4.0i)/(1.0+2.0i)=3.2-2.4i
Complex subtraction
(8.0+4.0i)-(1.0+2.0i)=7.0+2.0i
Number of active objects created=9
Ex.No.3 DATE CLASS
14
AIM
To design a Date class similar to the one provided in the java.util package.
ALGORITHM
i) Start
ii) Import theneededjavapackages
iii) Create object for dateclass
iv) Theobject callscorrespondingmethodtodonecessaryaction.
v) Stop
PROGRAM:
package exe3;
import java.util.*;
public class dateex {
static double y;
static double m;
static double d;
public long sec;
public int month,yr;
Scanner in=newScanner(System.in);
public void getms()
{
sec=System.currentTimeMillis();
System.out.println("Millisecond : "+sec);
}
public int getyr()
{
y=sec/(1000*60*60*24*365.25);
yr=(int)y;
int y1=yr+1970;
return y1;
}
public double getm()
{
double y=sec/(1000*60*60*24*365.25);
double x=y-(int)y;
m=x*12;
int m1=(int)m;
return m1;
}
public int getd(double m)
{
15
double d,a;
a=m-(int)m;
d=(a*30)+3;
//System.out.println("No of days : "+(int)d);
return (int)d;
}
public int getyr(int y1,int y2)
{
int i=y1;
int years=0;
while(i<y2)
{
if((i%4)==0)
years=years+366;
else
years+=365;
i++;
}
return years;
}
public int montodays(int m,int y)
{
int i=0,d=0;
while(i<m)
{
if(i<=7)
{
if((i%2)==0)
d=d+30;
else
d=d+31;
}
else if(i>=8)
{
if((i%2)==0)
d=d+31;
else
d=d+30;
}
i++;
}
return d;
}
public int getdifmon(int m1,int m2,int yr1,int yr2)
{
int mon1=this.montodays(m1,yr1);
16
int mon2=this.montodays(m2,yr2);
if((mon2-mon1)>0)
return (mon2-mon1);
else
return (mon1-mon2);
}
public void diff()
{
int yr1,yr2,y;
int m1,m2,m,d1,d2,d;
System.out.println("1st year : ");
yr1=in.nextInt();
System.out.println("1st month : ");
m1=in.nextInt();
System.out.println("1st date : ");
d1=in.nextInt();
System.out.println("2nd year : ");
yr2=in.nextInt();
System.out.println("2nd month : ");
m2=in.nextInt();
System.out.println("2nd date : ");
d2=in.nextInt();
y=this.getyr(yr1,yr2);
m=this.getdifmon(m1, m2, yr1, yr2);
d=d1-d2;
if(d<0)
d=-d;
int tot=y+m+d;
int year=yr2-yr1;
if(year<0)
year=-year;
int mon=m2-m1;
if(mon<0)
mon=-mon;
System.out.println("Total no of days = " +tot );
System.out.println("no of years= " +year );
System.out.println("no of month = " +mon );
System.out.println("no of day = " +d );
System.out.println("Difference = "+tot);
}
public static void main(String[] args)
{ Scanner in=new Scanner(System.in);
@SuppressWarnings("unused")
int year;
dateex a=newdateex();
a.getms();
int y=a.getyr();
17
double m=a.getm();
int d=a.getd(m);
switch((int)m)
{
case 0: System.out.println("Jan "+d+"," +y);break;
case 1: System.out.println("Feb "+d+"," +y);break;
case 2: System.out.println("Mar "+d+"," +y);break;
case 3: System.out.println("April "+d+"," +y);break;
case 4: System.out.println("May "+d+"," +y);break;
case 5: System.out.println("June "+d+"," +y);break;
case 6: System.out.println("July "+d+"," +y);break;
case 7: System.out.println("Aug "+d+"," +y);break;
case 8: System.out.println("Sep "+d+"," +y);break;
case 9: System.out.println("Oct "+d+"," +y);break;
case 10: System.out.println("Nov "+d+"," +y);break;
case 11: System.out.println("Dec "+d+"," +y);break;
}
a.diff();
a.getyr();
year=in.nextInt();
a.getleapyr();
}
public void getleapyr()
{
if(((yr%4)==0))
System.out.println("Given year is a leap year");
else
System.out.println("Given year is not a leap year");
}
}
Ex.No.4 DYNAMIC POLYMORPHISM
AIM
18
To develop with suitable hierarchy, classes for Point, Shape, Rectangle, Square,
Circle, Ellipse, Triangle, Polygon, etc. Design a simple test application to demonstrate
dynamic polymorphism.
ALGORITHM
i) Start
ii) Import neededjavapackages
iii) Createaclassesinthenameof circle, square, rectangular, triangle.
iv) Createobject foraboveclasses.
v) Theobject callscorrespondingmethodtodonecessaryaction.
vi) Stop
PROGRAM:
Draw.java
package ar;
public abstract class Draw {
abstract public void point();
}
Circle.java
package ar;
public class circle extends Draw{
private double rad;
public circle(double rad)
{
this.rad=rad;
}
void display()
{
System.out.println("The value of rad " + rad);
}
public void point()
{
double area=3.14*rad*rad;
System.out.println("The area of circle : "+area);
}
}
19
triangle.java
package ar;
public class triangle extends Draw{
private double base;
private double height;
public triangle(double base,double height)
{
this.base=base;
this.height=height;
}
void display()
{
System.out.println("The value of base " + base +"The value of
height"+height);
}
public void point()
{
double area=0.5*base*height;
System.out.println("The area of triangle : "+area);
}
}
square.java
package ar;
public class square extends Draw{
private double side;
public square(double side)
{
this.side=side;
}
void display()
{
System.out.println("The value of side " + side);
}
public void point()
{
double area=side*side;
System.out.println("The area of square : "+area);
}
}
rectangle.java
package ar;
20
public class rectangle extends Draw{
private double len,bre;
public rectangle(double len,double bre)
{
this.len=len;
this.bre=bre;
}
void display()
{
System.out.println("The value of length " + len + "The value of breadth :
"+bre);
}
public void point()
{
double area=len*bre;
System.out.println("The area of rectangle : "+area);
}
}
mainpoly.java
package ar;
public class mainpoly {
/**
* @param args
*/
void test(Draw v)
{
v.point();
}
void test1(Draw s)
{
if((s instanceof circle))
((circle)s).display();
else if((s instanceof triangle))
((triangle)s).display();
else if((s instanceof square))
((square)s).display();
else if((s instanceof rectangle))
((rectangle)s).display();
else
System.out.println("no object found");
}
21
public static void main(String[] args) {
triangle a=newtriangle(3.2,7.6);
square b=new square(2);
circle d=newcircle(2.4);
rectangle f=new rectangle(2,10);
mainpoly c=newmainpoly();
c.test1(a);
c.test(a);
c.test1(b);
c.test(b);
c.test1(d);
c.test(d);
c.test1(f);
c.test(f);
}
}
OUTPUT:
The value of base 3.2
The value of height7.6
The area of triangle : 12.16
The value of side 2.0
The area of square : 4.0
The value of rad 2.4
The area of circle : 18.086399999999998
The value of length 2.0
The value of breadth : 10.0
The area of rectangle : 20.0
Ex.No.5 JAVA INTERFACE USING ADT
AIM
To design a Java interface for ADT Stack. Develop two different classes that
implement this interface, one using array and the other using linked-list. Provide
necessary exception handling in both the implementations.
22
ALGORITHM
(i) Start
(ii) Constructthestack
(iii) Test if thestackislogicallyemptyreturntrueelsereturnfalse
(iv) UsingPOP(), themostrecentlyinserteditemcanberemoved.
(v) Usingpush(), thenewitemcanbeinsertedintothestack.
(vi) Stop
PROGRAM:
arraystack.java
package stack;
/**
* Array Based implementation of Stack
* @author Xyz
*/
public class arraystack implements stack{
private Object[] thearray;
private int topofstack;
private static final int DEFAULT_CAPACITY=10;
/**
* construct the stack
*/
public arraystack()
{
thearray= newObject[DEFAULT_CAPACITY];
topofstack=-1;
}
/**
* test if the stack is logically empty
* @return true if empty,false otherwise
*/
public boolean isempty()
{
return topofstack==-1;
}
/**
* Make the stack logically empty
*/
public void makeempty()
{
23
topofstack=-1;
}
/**
* get the most recently inserted element
*/
public Object top()
{
if(isempty())
thrownewRuntimeException("Array stack top");
return thearray[topofstack]; }
/**
* remove the most recently inserted item
*/
public Object pop(){
if(isempty())
thrownewRuntimeException("Array stack pop");
return thearray[topofstack--];
}
/**
* return and remove the most recently inserted item from stack
* @return the most recently inserted item in the stack
*/
public Object topandpop()
{
if(isempty())
thrownewRuntimeException("Array Stack top & pop");
return thearray[topofstack--];
}
/**
* insert a new item into the stack
* @param x the item to insert
*/
public void push(Object x)
{
if(topofstack+1==thearray.length)
doublearray();
thearray[++topofstack]=x;
}
/**
* Internal method to extend the array
*/
private void doublearray()
{
Object[] newarray;
newarray=newObject[thearray.length*2];
for(int i=0;i<thearray.length;i++)
newarray[i]=thearray[i];
24
thearray=newarray;
} }
stack.java
package stack;
public interface stack {
void push(Object x);
Object pop();
Object top();
Object topandpop();
boolean isempty();
void makeempty();
}
listnode.java
package stack;
public class listnode {
public Object element;
public listnode next;
public listnode(Object theelement)
{
this(theelement,null);
}
public listnode(Object theelement, listnode n) {
element=theelement;
next=n;
}}
UnderflowException.java
package stack;
public class UnderflowException extends RuntimeException{
public UnderflowException(String message)
{
super(message);
}}
linkedlist.java
package stack;
public class linkedlist implements stack {
25
private listnode topofstack;
public linkedlist(){
topofstack=null;
}
public boolean isempty() {
return topofstack==null;
}
public void makeempty() {
topofstack=null;
}
public Object pop() {
if(isempty())
thrownewUnderflowException("list stack pop");
return topofstack=topofstack.next;
}
public void push(Object x) {
topofstack=newlistnode(x,topofstack);
}
@Override
public Object top() {
if(isempty())
thrownewUnderflowException("List top of stack");
return topofstack.element ;
}
public Object topandpop() {
if(isempty())
thrownewUnderflowException("list of stack top & pop");
Object topitem=topofstack.element;
topofstack=topofstack.next;
return topitem;
}
}
stacktester.java
package stack;
public class stacktester {
public static void main(String[] args)
{
26
System.out.println("Stack using arrays linked list example");
arraystack as=new arraystack();
as.push(new String("a"));
as.push(new String("b"));
as.push(new String("c"));
System.out.println("Stack sing array elements -> a,b,c");
System.out.println("Stack LIFO & POP -> "+as.topandpop());
//as.pop();
System.out.println("Stack-->"+as.pop());
try
{
as.pop();
as.topandpop();
}
catch(RuntimeException rte)
{
System.err.println("exp occured while pop operation");
}
System.out.println("Stack using linked list example");
linkedlist ll=newlinkedlist();
ll.push(newInteger(10));
ll.push(newInteger(20));
ll.push(newInteger(30));
ll.push(newInteger(40));
System.out.println("Stack using linkedlist element -> 10,20,30,40");
System.out.println("Stack top->"+ll.top());
ll.pop();
ll.pop();
ll.pop();
ll.pop();
try{
ll.pop(); }
catch(RuntimeException rte) {
System.out.println("Exception occured while pop operation is
topped on stack by using linked list");
} } }
OUTPUT:
Stack using arrays linked list example
Stack sing array elements -> a,b,c
Stack LIFO & POP -> c
Stack-->b
Stack using linked list example
exp occured while pop operation
Stack using linkedlist element -> 10,20,30,40
Stack top->40
27
Exception occured while pop operation is topped on stack by using linked list
Ex.No.6 DNA SEQUENCE
AIM
To write a Java program to read a file that contains DNAsequences of arbitrary
length one per line (note that each DNAsequence is just a String). Your program should
sort the sequences in descending order with respect to the number of 'GC'
ALGORITHM
(i) Start
28
(ii) Import thenecessaryjavapackages
(iii) Createclassesandobject for respectiveclasses.
(iv) Createtwo text filesforsubsequencessearch.
(v) Stop
PROGRAM:
fileoperation.java
package thread;
import java.io.*;
import java.util.*;
public class FileOpeation {
public static String search_contents="TATA";
public static void main(String[] args)
{
String fi="Z:\\input.txt";
String out="Z:\\output.txt";
System.out.println("****************************");
System.out.println("DNA sequence eg by file read write operation");
System.out.println("****************************");
FileOpeation fo=new FileOpeation();
String content=fo.getfilecontent(fi);
fo.writetexttofile(content,out);
}
public void writetexttofile(String content, String filepath)
{
File oufile=null;
FileOutputStream fos=null;
BufferedOutputStream bos=null;
oufile=new File(filepath);
try
{ System.out.printf("\nSorted contents are written
into"+oufile.getCanonicalPath());
fos=new FileOutputStream(oufile);
bos= new BufferedOutputStream(fos);
bos.write(content.getBytes());
bos.close();
}
catch(IOException E)
{ E.printStackTrace(); }
}
public String getfilecontent(String filepath)
{
String content=null;
29
File file=new File(filepath);
FileReader fr=null;
BufferedReader br=null;
ArrayList<FileContent> filecontent=new ArrayList<FileContent>();
try
{
System.out.println("\nDNA sequence file is located
from["+file.getCanonicalPath()+"]");
System.out.println("\n-------------------");
fr=new FileReader(file);
br=new BufferedReader(fr);
int i=0;
String linestring=br.readLine();
while(linestring!=null)
{
System.out.println(linestring);
FileContent fc=new
FileContent(i++,getseqcount(linestring,search_contents),linestring);
filecontent.add(fc);
linestring=br.readLine();
}
fr.close();
br.close();
}
catch(FileNotFoundException E)
{
E.printStackTrace();
}
catch(IOException E)
{
E.printStackTrace();
}
System.out.println("\n_______________________");
System.out.println("\nContents are loaded to file sequence of
"+search_contents+"forstring the DNA contents");
content=sortlines(filecontent);
System.out.println("\nDNA sequence contents are sorted");
return content;
}
public String sortlines(ArrayList<FileContent> filecontent)
{
FileContent fc=null;
StringBuffer sb=new StringBuffer();
int i=0;
int[] seqarray=new int[5];
for(FileContent fc1:filecontent)
30
{
seqarray[i++]=fc1.getseqcont();
}
Arrays.sort(seqarray);
for(int itr=seqarray.length;itr>0;itr--)
{
for(int j=0;j<filecontent.size();j++)
{
fc=filecontent.get(j);
if(fc.getseqcont()==seqarray[itr-1])
{
sb.append(fc.getlinestring()+" ");
filecontent.remove(fc);
}
}
}
return sb.toString();
}
public int getseqcount(String ls,String text)
{
int seqcount=0;
if(ls!=null&&text!=null&&ls.contains(text))
{
int strlen=ls.length();
int s=0;
for(int i=0;i<strlen;i++)
{
if(ls.charAt(i)=='T');
{
i++;
if(ls.charAt(i)=='A')
{
i++;
if(ls.charAt(i)=='T')
{
i++;
if(ls.charAt(i)=='A')
{
s=s+1;
}
}
} }
} seqcount=s;
}
return seqcount; }}
FileContent.java
31
package thread;
public class FileContent {
private int lineno;
private int seqcount;
private String linestring;
public FileContent(int lineno,int seqcount, String linestring)
{
super();
this.lineno=lineno;
this.seqcount=seqcount;
this.linestring=linestring;
}
public int getseqcont()
{
return seqcount;
}
public void getseqcount(int seqcount)
{
this.seqcount=seqcount;
}
public String getlinestring()
{
return linestring;
}
public void getlinestring(String linestring)
{
this.linestring=linestring;
}
public int getlineno()
{
return lineno;
}
public void getlineno(int lineno)
{
this.lineno=lineno;
}
}
OUTPUT:
****************************
DNA sequence eg by file read write operation
****************************
DNA sequence file is located from[Z:\input.txt]
-------------------
32
TATAsdhhTATA
TATATATATATA
ahsdaghsdaTATA
_______________________
Contents are loaded to file sequence of TATA for string the DNA contents
DNA sequence contents are sorted
Sorted contents are written intoZ:\output.txt
INPUT FILE:
Input.txt
TATAsdhhTATA
TATATATATATA
ahsdaghsdaTATA
output.txt
TATATATATATA TATAsdhhTATA ahsdaghsdaTATA
Ex.No.7 PAINT APPLICATION
AIM
To develop a simple paint-like program that can draw basic graphical primitives in
different dimensions and colors. Use appropriate menu and buttons.
ALGORITHM
(i) Start
(ii) Createtheabstractparent classfordifferent shapeclasses.
(iii) Createthewindow
(iv) Createthemenu
(v) Select theappropriatemenuitemtodrawthecorrespondingshapes.
(vi) Stop.
33
PROGRAM:
DrawingPanel.java
package paint;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Panel;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class DrawingPanel extends Panel implements MouseListener{
private Point spoint=null;
private Point epoint=null;
private Shape shape=null;
private java.util.ArrayList list=new java.util.ArrayList();
public void paint(Graphics g)
{
g.setColor(Color.green);
shape.draw(list,g);
}
public void drawshape(Shape shape)
{
this.shape=shape;
}
public void mouseClicked(MouseEvent e)
{
if(shape instanceof TriangleShape)
{
list.add(e.getPoint());
if(list.size()>2)
{
repaint();
}
}
else if(shape instanceof PolygonShape)
{
list.add(e.getPoint());
if(list.size()>3)
{
repaint();
}
}
}
public void mouseEntered(MouseEvent e){}
34
public void mouseExited(MouseEvent e){}
public void mousePressed(MouseEvent e)
{
spoint=e.getPoint();
}
public void mouseReleased(MouseEvent e)
{
epoint=e.getPoint();
if(epoint.getX()<spoint.getX())
{
Point temp=epoint;
epoint=spoint;
spoint=temp;
}
if(epoint.getY()<spoint.getY()){
int temp=(int)epoint.getY();
epoint.y=(int)epoint.getY();
spoint.y=temp;
}
if(shape instanceof RectangleShape || shape instanceof OvalShape)
{
list.clear();
list.add(spoint);
list.add(epoint);
repaint();
}
}
}
Shape.java
package paint;
import java.util.*;
import java.awt.*;
public abstract class Shape {
/**abstract method draw()
* @return void
*/
public abstract void draw(java.util.List list,Graphics g);
} OvalShape.java
package paint;
import java.awt.Graphics;
35
import java.awt.Point;
import java.util.Iterator;
import java.util.List;
public class OvalShape extends Shape {
Point spoint=null;
Point epoint=null;
public void draw(List list, Graphics g) {
Iterator it=list.iterator();
if(list.size()<2)
{
return;
}
spoint=(Point)it.next();
epoint=(Point)it.next();
if(spoint==null||epoint==null)
{
return;
}
else
{
g.fillOval((int)spoint.getX(),(int)spoint.getY(),(int)(epoint.getX()-
spoint.getX()),(int)(epoint.getY()-spoint.getY()));
list.clear();
}
}
}
Rectangle.java
package paint;
import java.awt.Graphics;
import java.awt.Point;
import java.util.Iterator;
import java.util.List;
public class RectangleShape extends Shape {
Point spoint=null;
Point epoint=null;
@Override
public void draw(List list, Graphics g) {
Iterator it=list.iterator();
if(list.size()<2)
{
return;
}
spoint=(Point)it.next();
36
epoint=(Point)it.next();
if(spoint==null||epoint==null)
{
return;
}
else
{
g.fillRect((int)spoint.getX(),(int)spoint.getY(),(int)(epoint.getX()-
spoint.getX()),(int)(epoint.getY()-spoint.getY())); list.clear(); } }}
PolygonShape.java
package paint;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Polygon;
import java.util.Iterator;
import java.util.List;
public class PolygonShape extends Shape {
public void draw(java.util.List list, Graphics g) {
Iterator it=list.iterator();
if(list.size()<3)
{
return;
}
Polygon p=new Polygon();
for(;it.hasNext();)
{
Point point=(Point)it.next();
p.addPoint((int)point.getX(),(int)point.getY());
}
g.fillPolygon(p);
list.clear();
}}
TriangleShape.java
package paint;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Polygon;
import java.util.Iterator;
import java.util.List;
public class TriangleShape extends Shape {
37
Point spoint=null;
Point epoint=null;
@Override
public void draw(List list, Graphics g) {
Iterator it=list.iterator();
if(list.size()<3)
{
return;
}
Polygon p=newPolygon();
for(int i=0;i<3;i++)
{
Point point=(Point)it.next();
p.addPoint((int)point.getX(),(int)point.getY());
}
g.fillPolygon(p);
list.clear();
}}
SimpleDrawingTool.java
package paint;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JOptionPane;
public class SimpleDrawingTool extends Frame {
private static final int kcontrolA=65;
private static final int kcontrolD=68;
private static final int kcontrolC=67;
private static final int kcontrolR=82;
private static final int kcontrolP=80;
private static final int kcontrolT=84;
private static final int kcontrolX=88;
private RectangleShape rectangle=new RectangleShape();
private PolygonShape polygon=newPolygonShape();
private TriangleShape triangle=newTriangleShape();
private OvalShape oval=newOvalShape();
private DrawingPanel panel;
public SimpleDrawingTool(){
super("SimpleDrawingTool");
addMenu();
addPanel();
this.addWindowListener(newWindowHandler());
this.setSize(400,400);
38
this.setVisible(true);
}
public static void main(String args[])
{
SimpleDrawingTool sdt=newSimpleDrawingTool();
}
public void addPanel() {
MenuBar menubar=new MenuBar();
Menu file=newMenu("File");
Menu shape=newMenu("Shape");
Menu about=new Menu("About");
file.add(new MenuItem("Exit",new
MenuShortcut(kcontrolX))).addActionListener(newWindowHandler());
shape.add(new MenuItem("Rectangle",new
MenuShortcut(kcontrolR))).addActionListener(newWindowHandler());
shape.add(new MenuItem("Triangle",new
MenuShortcut(kcontrolT))).addActionListener(new WindowHandler());
shape.add(new MenuItem("Circle",new
MenuShortcut(kcontrolC))).addActionListener(newWindowHandler());
shape.add(new MenuItem("Polygon",new
MenuShortcut(kcontrolP))).addActionListener(new WindowHandler());
shape.add(new MenuItem("Draw Polygon",new
MenuShortcut(kcontrolD))).addActionListener(newWindowHandler());
about.add(newMenuItem("About",new
MenuShortcut(kcontrolA))).addActionListener(newWindowHandler());
menubar.add(file);
menubar.add(shape);
menubar.add(about);
if(null==this.getMenuBar())
{
this.setMenuBar(menubar);
} }
private void addMenu() {
panel=new DrawingPanel();
Dimension d=this.getSize();
Insets ins=this.insets();
d.height=d.height-ins.top-ins.bottom;
d.width=d.width-ins.left-ins.right ;
panel.setSize(d);
panel.setLocation(ins.left,ins.top) ;
panel.addMouseListener(panel);
this.add(panel);
}
private class WindowHandler extends WindowAdapter implements
ActionListener{
public void windowClosing(WindowEvent e){
39
System.exit(0);
}
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equalsIgnoreCase("exit"))
{
System.exit(0);
}
else if(e.getActionCommand().equalsIgnoreCase( "Rectangle"))
{
Menu menu=getMenuBar().getMenu(1);
for(int
i=0;i<menu.getItemCount();menu.getItem(i).setEnabled(true),i++);
getMenuBar().getShortcutMenuItem(new
MenuShortcut(kcontrolR)).setEnabled(false);
panel.drawshape(rectangle);
}
else if(e.getActionCommand().equalsIgnoreCase( "Circle"))
{
Menu menu=getMenuBar().getMenu(1);
for(int
i=0;i<menu.getItemCount();menu.getItem(i).setEnabled(true),i++);
getMenuBar().getShortcutMenuItem(new
MenuShortcut(kcontrolC)).setEnabled(false);
panel.drawshape(oval);
}
else if(e.getActionCommand().equalsIgnoreCase( "Triangle"))
{
Menu menu=getMenuBar().getMenu(1);
for(int
i=0;i<menu.getItemCount();menu.getItem(i).setEnabled(true),i++);
getMenuBar().getShortcutMenuItem(new
MenuShortcut(kcontrolT)).setEnabled(false);
panel.drawshape(triangle);
}
else if(e.getActionCommand().equalsIgnoreCase( "Polygon"))
{
Menu menu=getMenuBar().getMenu(1);
for(int
i=0;i<menu.getItemCount();menu.getItem(i).setEnabled(true),i++);
getMenuBar().getShortcutMenuItem(new
MenuShortcut(kcontrolP)).setEnabled(false);
panel.drawshape(polygon);
}
else if(e.getActionCommand().equalsIgnoreCase( "DrawPolygon"))
{
Menu menu=getMenuBar().getMenu(1);
40
for(int
i=0;i<menu.getItemCount();menu.getItem(i).setEnabled(true),i++);
getMenuBar().getShortcutMenuItem(new
MenuShortcut(kcontrolD)).setEnabled(false);
panel.repaint();
}
else if(e.getActionCommand().equalsIgnoreCase( "about"))
{
JOptionPane.showMessageDialog(null,"This small paint
like pgm","About",JOptionPane.PLAIN_MESSAGE);
} } }}
OUTPUT:
41
Ex.No.8 SCIENTIFIC CALCULATOR
AIM
To develop a scientific calculator using even-driven programming paradigm of
Java.
ALGORITHM
(i) Start
(ii) Import neededjavapackageespeciallyswing.
(iii) Createapanel.
(iv) Createaframe
(v) Createsanewfont fromthespecifiedname, styleand pointssize
(vi) Set uptheJmenubarhaveprovidedall Jmenu' swithmnemonics.
(vii) Stop
PROGRAM:
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
public class Scientific extends JFrame implements ActionListener{
42
JTextField tfield;
double temp,temp1,result,a;
static double m1,m2;
int k=1,x=0,y=0,z=0;
char ch;
JButton b1,b2,b3,b4,b5,b6,b7,b8,b9,zero,clr,plus,min,div,mul,eq,sqrt,cos;
Container cont;
JPanel textpanel,buttonpanel;
Scientific(){
cont=getContentPane();
cont.setLayout(new BorderLayout());
JPanel textpanel=newJPanel();
tfield=new JTextField(25);
tfield.setHorizontalAlignment(SwingConstants.RIGHT);
tfield.addKeyListener(new KeyAdapter(){
public void keyTyped(KeyEvent keyevent){
char c=keyevent.getKeyChar();
if(c>='0'&&c<='9'){
}else{
keyevent.consume();
}
}
});
textpanel.add(tfield);
buttonpanel=newJPanel();
buttonpanel.setLayout(new GridLayout(8,4,2,2));
boolean t=true;
b1=newJButton("1");
buttonpanel.add(b1);
b1.addActionListener(this);
b2=newJButton("2");
buttonpanel.add(b2);
b2.addActionListener(this);
b3=newJButton("3");
buttonpanel.add(b3);
b3.addActionListener(this);
b4=newJButton("4");
buttonpanel.add(b4);
b4.addActionListener(this);
b5=newJButton("5");
buttonpanel.add(b5);
43
b5.addActionListener(this);
b6=newJButton("6");
buttonpanel.add(b6);
b6.addActionListener(this);
b7=newJButton("7");
buttonpanel.add(b7);
b7.addActionListener(this);
b8=newJButton("8");
buttonpanel.add(b8);
b8.addActionListener(this);
b9=newJButton("9");
buttonpanel.add(b9);
b9.addActionListener(this);
zero=newJButton("0");
buttonpanel.add(zero);
zero.addActionListener(this);
plus=new JButton("+");
buttonpanel.add(plus);
plus.addActionListener(this);
min=new JButton("-");
buttonpanel.add(min);
min.addActionListener(this);
mul=new JButton("*");
buttonpanel.add(mul);
mul.addActionListener(this);
div=newJButton("/");
buttonpanel.add(div);
div.addActionListener(this);
eq=newJButton("=");
buttonpanel.add(eq);
eq.addActionListener(this);
sqrt=newJButton("Sqrt");
buttonpanel.add(sqrt);
sqrt.addActionListener(this);
44
clr=newJButton("AC");
buttonpanel.add(clr);
clr.addActionListener(this);
cos=newJButton("Cos");
buttonpanel.add(cos);
cos.addActionListener(this);
cont.add("Center",buttonpanel);
cont.add("North",textpanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
String s=e.getActionCommand();
System.out.println(s);
if(s.equals("1")){
if(z==0){
tfield.setText(tfield.getText()+"1");
}else{
tfield.setText("");
tfield.setText(tfield.getText()+"1");
z=0;
}
}
if(s.equals("2")){
if(z==0){
tfield.setText(tfield.getText()+"2");
}else{
tfield.setText("");
tfield.setText(tfield.getText()+"2");
z=0;
}
}
if(s.equals("3")){
if(z==0){
tfield.setText(tfield.getText()+"3");
}else{
tfield.setText("");
tfield.setText(tfield.getText()+"3");
z=0;
}
}
if(s.equals("4")){
if(z==0){
tfield.setText(tfield.getText()+"4");
45
}else{
tfield.setText("");
tfield.setText(tfield.getText()+"4");
z=0;
}
}
if(s.equals("5")){
if(z==0){
tfield.setText(tfield.getText()+"5");
}else{
tfield.setText("");
tfield.setText(tfield.getText()+"5");
z=0;
}
}
if(s.equals("6")){
if(z==0){
tfield.setText(tfield.getText()+"6");
}else{
tfield.setText("");
tfield.setText(tfield.getText()+"6");
z=0;
}
}
if(s.equals("7")){
if(z==0){
tfield.setText(tfield.getText()+"7");
}else{
tfield.setText("");
tfield.setText(tfield.getText()+"7");
z=0;
}
}
if(s.equals("8")){
if(z==0){
tfield.setText(tfield.getText()+"8");
}else{
tfield.setText("");
tfield.setText(tfield.getText()+"8");
z=0;
}
}
if(s.equals("9")){
if(z==0){
tfield.setText(tfield.getText()+"9");
}else{
tfield.setText("");
46
tfield.setText(tfield.getText()+"9");
z=0;
}
}
if(s.equals("0")){
if(z==0){
tfield.setText(tfield.getText()+"0");
}else{
tfield.setText("");
tfield.setText(tfield.getText()+"0");
z=0;
}
}
if(s.equals("+")){
if(tfield.getText().equals("")){
tfield.setText("");
temp=0;
ch='+';
}else{
temp=Double.parseDouble(tfield.getText());
tfield.setText("");
ch='+';
x=0;
y=0;
}
tfield.requestFocus();
}
if(s.equals("-")){
if(tfield.getText().equals("")){
tfield.setText("");
temp=0;
ch='-';
}else{
temp=Double.parseDouble(tfield.getText());
tfield.setText("");
ch='-';
x=0;
y=0;
}
tfield.requestFocus();
}
if(s.equals("*")){
if(tfield.getText().equals("")){
tfield.setText("");
temp=0;
ch='*';
}else{
47
temp=Double.parseDouble(tfield.getText());
tfield.setText("");
ch='*';
x=0;
y=0;
}
tfield.requestFocus();
}
if(s.equals("/")){
if(tfield.getText().equals("")){
tfield.setText("");
temp=0;
ch='/';
}else{
temp=Double.parseDouble(tfield.getText());
tfield.setText("");
ch='/';
x=0;
y=0;
}
tfield.requestFocus();
}
if(s.equals("Sqrt")){
if(tfield.getText().equals("")){
tfield.setText("");
}else{
a=Math.sqrt(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText()+a);
}
}
if(s.equals("Cos")){
if(tfield.getText().equals("")){
tfield.setText("");
}else{
a=Math.cos(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText()+a);
}
}
if(s.equals("AC")){
tfield.setText("");
x=0;y=0;z=0;
}
if(s.equals("=")){
if(tfield.getText().equals("")){
tfield.setText("");
48
}else{
temp1=Double.parseDouble(tfield.getText());
switch(ch){
case'+':result=temp+temp1;
break;
case '-':result=temp-temp1;
break;
case '*':result=temp*temp1;
break;
case '/': result=temp/temp1;
break;
}
tfield.setText("");
System.out.println(result);
tfield.setText(tfield.getText()+result);
z=1;
}
}
tfield.requestFocus();
}
public static void main(String args[]){
try{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookA
ndFeel");
}
catch(Exception e){
}
Scientific f=newScientific();
f.setTitle("Scientific Calculator");
f.pack();
f.setVisible(true);
}}
OUTPUT:
8
+
8
=
16.0
49
50
Ex.No.9 LINKED-LIST CLASS USING TEMPLATE
AIM
To develop a template for linked-list class along with its methods in Java.
ALGORITHM
i) Start
ii) Constructthelist
iii) Test if thelist islogicallyempty, returntrueelsefalse
iv) Constructthelist iterator.
v) Test if thecurrent positionisvalidpositioninthelist andreturntrue.
vi) Stop.
PROGRAM:
LinkedList.java
import java.util.Scanner;
public class LinkedList<T> {
public void create(ListNode<T> top,T data)
{
top.element=data;
top.next=null;
}
void display(ListNode<T> list)
{
while(list.next!=null)
{
System.out.println(list.element);
list=list.next;
}
System.out.println(list.element);
}
int count(ListNode<T> list)
{
int cnt=0;
while(list.next!=null)
{
list=list.next;
cnt++;
}
cnt++;
return(cnt);
}
ListNode<T> insert(ListNode<T> list,T data)
51
{
int pos,cnt,loc=1;
ListNode<T> cur=list;
ListNode<T> pre=null;
ListNode<T> n;
System.out.println("enter the position:");
Scanner p=newScanner(System.in);
pos=p.nextInt();
cnt=count(list);
if((pos<0)||(pos>cnt))
System.out.println("out of range");
else
{
if(pos==1)
{
pre=newListNode<T>(data,cur);
return pre;
}
else
{
while(loc<pos)
{
pre=cur;
cur=cur.next;
loc++;
}
n=newListNode<T>(data,cur);
pre.next=n;
}
}
return list;
}
ListNode<T> del(ListNode<T> list)
{
int pos,cnt,loc=1,d=1;
ListNode<T> cur=list;
ListNode<T> pre=null;
System.out.println("linear link list delete");
System.out.println("Entr the position:");
Scanner p=newScanner(System.in);
pos=p.nextInt();
cnt=count(list);
if((pos<0)||(pos>(cnt+1)))
{
System.out.println("position is out of range");
}
52
else
{
if(pos==1)
{
if(list.next==null)
{
list=list.next;
System.out.println("link empty");
return list;
}
else{
while(list.next!=null)
{
list=list.next;
return list;
}
}
}
else{
while(loc<pos)
{
pre=cur;
cur=cur.next;
loc++;
}
pre.next=cur.next;
}}
return list;
}
public boolean isEmpty(ListNode<T>list)
{
if(list != null)
return true;
return list==null;
}
public void modify(T m,T p,ListNode<T> list)
{
while(list.next!=null)
{
boolean i=m.equals(list.element);
if(i)
{
53
System.out.println("found");
list.element=p;
System.out.println("modified");
break;
}
list=list.next;
}
boolean i=m.equals(list.element);
if(i)
{ System.out.println("found");
list.element=p;
System.out.println("modified");
}
}
public void find(T m,ListNode<T>list)
{
while(list!=null)
{
boolean i=m.equals(list.element);
if(i)
{
System.out.println("present");
return;
}
list=list.next;
}
if(list==null)
System.out.println("not present");
return;
}}
ListNode:
public class ListNode<T> {
public T element;
public ListNode<T> next;
public ListNode(T theelement)
{
this(theelement,null);
}
public ListNode(T ele,ListNode<T> n)
{
element=ele;
next=n;
}}
54
MainTester.java
import java.util.Scanner;
public class MainTester {
public static void main(String args[])
{
ListNode<String>head=newListNode<String>(null);
LinkedList<String>list=new LinkedList<String>();
int ch;
System.out.println("enter the first node:");
Scanner s=new Scanner(System.in);
String s1=s.nextLine();
list.create(head,s1);
list.display(head);
while(true)
{
System.out.println("1.insert\t2.delete\t3.replace\t4.display\t5.find\t6.exit");
Scanner p=newScanner(System.in);
ch=p.nextInt();
switch(ch)
{
case 1:
System.out.println("enter the data:");
Scanner p1=newScanner(System.in);
String ps=p1.nextLine();
head=list.insert(head,ps);
list.display(head);
break;
case 2:
head=list.del(head);
list.display(head);
break;
case 3:
System.out.println("enter the string to be replaced:");
Scanner sc=newScanner(System.in);
String sc1=sc.nextLine();
System.out.println("enter the new String:");
Scanner sa=newScanner(System.in);
String sa1=sa.nextLine();
list.modify(sc1,sa1,head);
break;
case 4:
list.display(head);
break;
case 5:
System.out.println("enter the element to be found:");
55
Scanner sf=new Scanner(System.in);
String sf1=sf.nextLine();
list.find(sf1, head);
break;
case 6:
System.exit(0);
}
}}}
OUTPUT:
enter the first node:
33
33
1.insert 2.delete 3.replace 4.display 5.find 6.exit
1
enter the data:
22
enter the position:
1
22
33
1.insert 2.delete 3.replace 4.display 5.find 6.exit
1
enter the data:
67
enter the position:
2
22
67
33
1.insert 2.delete 3.replace 4.display 5.find 6.exit
5
enter the element to be found:
33
present
1.insert 2.delete 3.replace 4.display 5.find 6.exit
4
22
BAT
33
1.insert 2.delete 3.replace 4.display 5.find 6.exit
3
enter the string to be replaced:
67
enter the new String:
88
found
modified
56
1.insert 2.delete 3.replace 4.display 5.find 6.exit
4
22
88
33
1.insert 2.delete 3.replace 4.display 5.find 6.exit
2
linear link list delete
Entr the position:
2
22
33
1.insert 2.delete 3.replace 4.display 5.find 6.exit
6
Ex.No.10 PRODUCER-CONSUMER USING THREAD
AIM
57
To design a thread-safe implementation of Queue class. Write a multi-threaded
producer-consumer application that uses this Queue class.
ALGORITHM
i) Start
ii) Createconstructorinthenameof customerwithtwoargument.
iii) Createaclasscubbyhole.
iv) Createaclassproducer.
v) Createtheobject of aboveclasses.
vi) Theobjectscall theappropriatemethodanddothenecessaryaction.
vii) Stop.
PROGRAM:
cubbyhole.java
package exe9;
public class cubbyhole {
private int contents;
private boolean available=false;
public synchronized int get()
{
while(available==false)
{
try{
wait();
}
catch(InterruptedException E){}
}
available=false;
notifyAll();
return contents;
}
public synchronized void put(int value)
{
while(available==true)
{
try{
wait();
}
catch(InterruptedException E){ }
}
contents=value;
58
available=true;
notifyAll();
}}
consumer.java
package exe9;
public class consumer extends Thread {
private cubbyhole ch;
private int number;
public consumer(cubbyhole c,int number)
{
ch=c;
this.number=number;
}
public void run()
{
int value=0;
for(int i=0;i<10;i++)
{
value=ch.get();
System.out.println("Consumer#"+this.number+"got"+value);
}
}
}
producer.java
package exe9;
public class producer extends Thread{
private cubbyhole ch;
private int no;
public producer(cubbyhole c,int no){
ch=c;
this.no=no;
}
public void run()
{
for(int i=0;i<10;i++)
{
ch.put(i);
System.out.println("Producer #"+this.no+"put"+i);
try{
sleep((int)(Math.random()*100));
}
catch(InterruptedException E){}
}
59
} }
ProConsTest.java
package exe9;
public class ProConsTest {
public static void main(String[] args){
cubbyhole c=new cubbyhole();
producer p1=new producer(c,1);
consumer c1=new consumer(c,1);
p1.start(); c1.start(); }}
OUTPUT:
Producer #1put0
Consumer#1got0
Consumer#1got1
Producer #1put1
Consumer#1got2
Producer #1put2
Consumer#1got3
Producer #1put3
Consumer#1got4
Producer #1put4
Producer #1put5
Consumer#1got5
Consumer#1got6
Producer #1put6
Consumer#1got7
Producer #1put7
Consumer#1got8
Producer #1put8
Consumer#1got9
Producer #1put9
Ex.No.11 MULTI-THREADED PROGRAM
AIM
To write a multi-threaded Java program to print all numbers below 100,000 that
are both prime and Fibonacci number (some examples are 2, 3, 5, 13, etc.). Design a
60
thread that generates prime numbers below 100,000 and writes them into a pipe. Design
another thread that generates fibonacci numbers and writes them to another pipe. The
main thread should read both the pipes to identify numbers common to both.
ALGORITHM
i) Start
ii) Createclasspipedstreamtester whichextendsthreadclass.
iii) CreateaclassFibonacci numbergeneratorwhichextendsthreadclass.
iv) Createaclassprimenumbergenerator whichextendsthreadclass.
v) Executemainthread.
vi) Stop.
PROGRAM:
FIBONACCIMUMBERGENERATOR:
package pipe;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PipedOutputStream;
public class FibonacciNumberGenerator extends Thread{
private DataOutputStream dos;
public FibonacciNumberGenerator(ThreadGroup threadgroup,PipedOutputStream
pis,String name)
{
super(threadgroup,name);
dos=new DataOutputStream(pis);
}
public void run()
{
try{
for(int k=0;k<10000;k++)
{
long fibonacciNum=Fib(k);
if(fibonacciNum >=0 && fibonacciNum<10000)
{
dos.writeLong(fibonacciNum);
dos.flush();
}
}
}
catch(IOException e)
{
61
}}
public int Fib(int n)
{
int prev1=0,prev2=1;
for(int i=0;i<n;i++)
{
int save_prev1=prev1;
prev1=prev2;
prev2=save_prev1+prev2;
}
return prev1;
}
}PipedStreamReader.java
package pipe;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class PipedStreamTester extends Thread{
DataInputStream fibonicpis;
DataInputStream primepis;
public PipedStreamTester(PipedInputStream fibonicpis,PipedInputStream primepis)
{
this.fibonicpis=new DataInputStream (fibonicpis);
this.primepis=new DataInputStream (primepis);
}
public static void main(String[] args){
try{
PipedOutputStream fibonicpos=newPipedOutputStream();
PipedInputStream fibonicpis=new PipedInputStream(fibonicpos);
PipedOutputStream primepos=new PipedOutputStream();
PipedInputStream primepis=new PipedInputStream(primepos);
ThreadGroup ty=newThreadGroup("piped thread");
FibonacciNumberGenerator f=new
FibonacciNumberGenerator(ty,fibonicpos,"fibonaccinumbergenerator");
PrimeNumberGenerator p=new
PrimeNumberGenerator(ty,primepos,"primenumbergenerator");
PipedStreamTester maintester=new
PipedStreamTester(fibonicpis,primepis);
maintester.start();
f.start();
p.start();
62
}catch(IOException e){
e.printStackTrace();
}
}
public void run()
{
boolean canrun=true;
boolean cangoprimeloop=true;
boolean cangofibonicloop=true;
long primenumber=-1L;
long fibonicnumber=-1L;
while(canrun)
{
if(fibonicpis!=null&&cangofibonicloop)
{
try
{
fibonicnumber=fibonicpis.readLong();
System.out.println("fibonicnumber#>"+fibonicnumber);
}catch(IOException e){
cangofibonicloop=false;
}
}
if(primepis!=null&&cangoprimeloop)
{
try
{
primenumber=primepis.readLong();
System.out.println("primenumber#>"+primenumber);
}catch(IOException e){
cangoprimeloop=false;
}
}
}}}
PrimeNumberGenerator:
package pipe;
63
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PipedOutputStream;
public class PrimeNumberGenerator extends Thread
{
private DataOutputStream dos;
public PrimeNumberGenerator(ThreadGroup threadgroup,PipedOutputStream pos,String name)
{
super(threadgroup,name);
dos=new DataOutputStream(pos);
}public void run()
{
try
{
int x,y;
for(x=2;x<10000;x++)
{
if(x%2!=0||x==2)
{
for(y=2;y<=x/2;y++)
{
if(x%y==0)
{
break;
}
}
if(y>x/2)
{
if(x<10000)
{
dos.writeLong(x);
dos.flush();
} }
} }
}
catch(IOException e)
{} } }
OUTPUT:
fibonicnumber#>0
primenumber#>2
fibonicnumber#>1
primenumber#>3
fibonicnumber#>1
primenumber#>5
fibonicnumber#>2
primenumber#>7
64
fibonicnumber#>3
primenumber#>11
fibonicnumber#>5
primenumber#>13
fibonicnumber#>8
primenumber#>17
fibonicnumber#>13
primenumber#>19
65
Ex.No.12 GUI MULTI-THREADED PROGRAM
AIM:
To develop a multi-threaded GUI application of your choice.
PROGRAM:
package mygame;
import java.io.*;
public class Fileop {
static File file=new File("C:\\Happy birds\\SystemFiles\\highscores.txt");
int num=0;
static int[] scores=new int[3];
static String finalvalue;
public Fileop(){
try{
FileReader fr=new FileReader(file);
BufferedReader br=new BufferedReader(fr);
while(num<3){
scores[num]=(int)Double.parseDouble(br.readLine());
num++;
}
}catch(IOException e)
{}
}
public static void writetofile()
{
try{
FileWriter write = new FileWriter(file);
PrintWriter print= new PrintWriter(write);
for(int i=0;i<3;i++){
print.println(scores[i]);
}
print.close();
write.close();
}
catch(IOException e)
{}
}
}
66
package mygame;
import java.io.*;
public class Fileop {
static File file=new File("C:\\Happy birds\\SystemFiles\\highscores.txt");
int num=0;
static int[] scores=new int[3];
static String finalvalue;
public Fileop(){
try{
FileReader fr=new FileReader(file);
BufferedReader br=new BufferedReader(fr);
while(num<3){
scores[num]=(int)Double.parseDouble(br.readLine());
num++;
}
}catch(IOException e)
{}
}
public static void writetofile()
{
try{
FileWriter write = new FileWriter(file);
PrintWriter print= new PrintWriter(write);
for(int i=0;i<3;i++){
print.println(scores[i]);
}
print.close();
write.close();
}
catch(IOException e)
{}
}
}
package mygame;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
67
public class highscores extends JPanel implements MouseListener {
Image img=Toolkit.getDefaultToolkit().getImage("C:\\Happy
Birds\\Imagefiles\\highscores.jpg");
public highscores()
{
addMouseListener(this);
}
public void paintComponent(Graphics g)
{
g.drawImage(img,0,0,this);
g.setColor(zeroshotframe.mc);
g.setFont(new Font("Angrybirds",Font.PLAIN,85));
g.drawString(""+Fileop.scores[0],600,270);
g.drawString(""+Fileop.scores[1],600,365);
g.drawString(""+Fileop.scores[2],600,460);
}
public void mouseClicked(MouseEvent e) {
this.setVisible(false);
zeroshotframe.l1.setVisible(true);
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
}
package mygame;
import javax.swing.*;
import java.awt.*;
68
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class htpscreen extends JPanel implements MouseListener
{
Image img=Toolkit.getDefaultToolkit().getImage("C:\\Happy
birds\\ImageFiles\\howtoplayscreen.jpg");
public htpscreen()
{
addMouseListener(this);
}
public void paint(Graphics g)
{
g.drawImage(img,0,0,this);
}
public void mouseClicked(MouseEvent arg0)
{
this.setVisible(false);
zeroshotframe.z1.setVisible(true);
}
public void mousePressed(MouseEvent arg0){}
public void mouseReleased(MouseEvent arg0){}
public void mouseEntered(MouseEvent arg0){}
public void mouseExited(MouseEvent arg0){}
}
package mygame;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.InputStream;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
69
public class last extends JPanel implements MouseListener
{
Image bg=Toolkit.getDefaultToolkit().getImage("C:\\Happy
birds\\ImageFiles\\end.jpg");
Image bg2=Toolkit.getDefaultToolkit().getImage("C:\\Happy
birds\\ImageFiles\\highend.jpg");
ImageIcon sg=new ImageIcon("D:\\Happy birds\\ImageFiles\\buttonsmall.gif");
JButton b1=new JButton(sg);
JButton b2=new JButton(sg);
JPanel p1=new JPanel();
public last()
{
b1.setOpaque(false);
b1.setContentAreaFilled(false);
b1.setBorderPainted(false);
b1.setEnabled(true);
b2.setOpaque(false);
b2.setContentAreaFilled(false);
b2.setBorderPainted(false);
b2.setEnabled(true);
p1.setOpaque(false);
setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
add(Box.createRigidArea(new Dimension(350,270)));
add(p1);
p1.add(b1);
p1.add(Box.createRigidArea(new Dimension(260,290)));
p1.add(b2);
b1.setCursor(new Cursor(Cursor.HAND_CURSOR));
b2.setCursor(new Cursor(Cursor.HAND_CURSOR));
b1.addMouseListener(this);
b2.addMouseListener(this);
}
public void paint(Graphics g)
{
if(zeroshot2.scorechange==true)
g.drawImage(bg2,0,0,this);
else
g.drawImage(bg,0,0,this);
g.setColor(zeroshotframe.mc);
g.setFont(new Font("Angrybirds",Font.PLAIN,100));
g.drawString(""+zeroshot2.score,630,250);
}
70
public void mouseClicked(MouseEvent e)
{
if(e.getSource()==b1)
{
zeroshot2.score=0;
timethread.mytime=60;
zeroshot2.time=60;
zeroshot2.scorechange=false;
main.z.create1();
}
if(e.getSource()==b2)
{
main.z.highs();
}
}
public void mousePressed(MouseEvent arg0) {}
public void mouseReleased(MouseEvent arg0) {}
public void mouseEntered(MouseEvent arg0) {}
public void mouseExited(MouseEvent arg0) {}
}
package mygame;
import java.applet.Applet;
import java.applet.AudioClip;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.*;
public class main extends Applet{
public static zeroshotframe z=new zeroshotframe();
static AudioClip ad;
boolean x=true;
AudioClip song[ ] = new AudioClip[3];
public void init()
{
try
{
File f=new File("C:\\Happy birds\\SystemFiles");
URL url=new URL(f.toURL(),"");
AudioClip ad=getAudioClip(url,"locowav.wav");
71
z.create1();
while(true)
{
if(x){
ad.loop();
x=false;
}
}
}
catch(MalformedURLException e){}
}
}
package mygame;
public class mythread extends Thread
{
public int x,k=0;
public int y;
int num=0;
public void run()
{
myrandom();
while(zeroshot2.time>0)
{
try
{
sleep(800);
change();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
main.z.last();
this.stop();
}
public void change()
72
{
myrandom();
zeroshotframe.z2.setvisible(x);
}
public void myrandom()
{
x=(int)((1000*105*Math.random()+5)%main.z.z2.number);
if(x==y||x==y+1||x==y-1)
{
myrandom();
}
y=x;
}
}
package mygame;
import java.awt.Color;
import java.awt.Font;
public class timethread extends Thread{
static int mytime=60;
public void run()
{
while(mytime>0){
zeroshot2.time=mytime--;
main.z.z2.repaint();
try {
sleep(1000);
if(mytime%10==0)
zeroshot2.occur=false;
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
zeroshot2.time--;
this.stop();
}
73
}
package mygame;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
public class zeroshot1 extends JPanel implements MouseListener
{
Image bg=Toolkit.getDefaultToolkit().getImage("C:\\Happy
birds\\ImageFiles\\happybirds.jpg");
ImageIcon sg=new ImageIcon("C:\\Happy birds\\ImageFiles\\buttonsmall.gif");
JButton startgame=new JButton(sg);
JButton howtoplay=new JButton(sg);
JPanel p1=new JPanel();
public zeroshot1()
{
p1.setLayout(new BoxLayout(p1,BoxLayout.X_AXIS));
startgame.setOpaque(true);
startgame.setContentAreaFilled(false);
startgame.setBorderPainted(false);
howtoplay.setOpaque(true);
howtoplay.setContentAreaFilled(false);
howtoplay.setBorderPainted(false);
p1.add(startgame);
p1.add(Box.createRigidArea(new Dimension(240,290)));
p1.add(howtoplay);
p1.setOpaque(false);
startgame.addMouseListener(this);
howtoplay.addMouseListener(this);
74
startgame.setCursor(new Cursor(Cursor.HAND_CURSOR));
howtoplay.setCursor(new Cursor(Cursor.HAND_CURSOR));
setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
add(Box.createRigidArea(new Dimension(0,330)));
add(p1);
}
public void mouseClicked(MouseEvent e )
{ if(e.getSource()==startgame)
{
main.z.exe();
}
if(e.getSource()==howtoplay)
{
main.z.create2();
}
this.setVisible(false);
}
public void mousePressed(MouseEvent arg0){}
public void mouseReleased(MouseEvent arg0){}
public void mouseEntered(MouseEvent arg0){}
public void mouseExited(MouseEvent arg0){}
public void paint(Graphics g)
{
g.drawImage(bg,0,0,this);
}
}
package mygame;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
75
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
public class zeroshot2 extends JPanel implements ActionListener
{
Image bg2=Toolkit.getDefaultToolkit().getImage("C:\\Happy
birds\\ImageFiles\\second2.jpg");
static ImageIcon pig=new ImageIcon("C:\\Happy birds\\ImageFiles\\pig.jpg");
static ImageIcon bird=new ImageIcon("C:\\Happy birds\\ImageFiles\\bird3.jpg");
public int picdis=110;
boolean oncebird=true;
static final int number=30;
static int score=0,time=60;
public int k=1;
static boolean occur=false;
JPanel p1=new JPanel();
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JButton[] object=new JButton[number];
int randomizer=1,previous;
int a;
boolean previcon=false;
static boolean scorechange=false;
public zeroshot2()
{
for(int i=0;i<number;i++)
{
object[i]=new JButton(pig);
object[i].addActionListener(this);
object[i].setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
object[i].setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
object[i].setVisible(false);
}
for(int i=0;i<10;i++)
{
p1.add(object[i]);
p1.add(Box.createRigidArea(new Dimension(picdis,picdis)));
}
for(int i=10;i<20;i++)
{
p2.add(object[i]);
p2.add(Box.createRigidArea(new Dimension(picdis,picdis)));
}
76
for(int i=20;i<30;i++)
{
p3.add(object[i]);
p3.add(Box.createRigidArea(new Dimension(picdis,picdis)));
}
setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
p1.setOpaque(false);
p2.setOpaque(false);
p3.setOpaque(false);
add(Box.createRigidArea(new Dimension(50,150)));
add(p1);
add(p2);
add(p3);
}
public void paintComponent(Graphics g)
{
g.drawImage(bg2,0,0,this);
g.setColor(zeroshotframe.mc);
g.setFont(new Font("Angrybirds",Font.PLAIN,65));
g.drawString(""+score,1205,85);
g.drawString(""+time,155,85);
}
public void setvisible(int x)
{
for(int i=0;i<number;i++)
{
if(i!=x)
{
object[i].setVisible(false);
}
}
if(previcon==true)
{
object[previous].setIcon(pig);
previcon=false;
}
if(occur==false){
a=(int)((Math.random()*100000000)%10);
System.out.println(a);
if(a==1||a==7)
{
object[x].setIcon(bird);
previcon=true;
previous=x;
occur=true;
77
}
}
object[x].setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(previcon==true)
{
if(oncebird==true){
if(score>50)
score-=50;
else
score=0;
oncebird=false;
}
}
else
score+=10;
oncebird=true;
repaint();
}
public static void checkscores()
{
for(int i=0;i<3;i++){
if(score>Fileop.scores[i])
{
if(i==0){
Fileop.scores[i+2]=Fileop.scores[i+1];
Fileop.scores[i+1]=Fileop.scores[i];
}
else if(i==1)
{
Fileop.scores[i+1]=Fileop.scores[i];
}
Fileop.scores[i]=score;
scorechange=true;
break;
}
78
}
}
}
package mygame;
import java.awt.*;
import javax.swing.JFrame;
public class zeroshotframe extends JFrame
{
public static zeroshot2 z2=new zeroshot2();
public static zeroshot1 z1=new zeroshot1();
public static htpscreen h1=new htpscreen();
public static highscores hi=new highscores();
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
public static last l1=new last();
Fileop fileop=new Fileop();
static Color mc=new Color(3,45,140);
public zeroshotframe(){
super("Happy Birds");
}
public void create1()
{
l1.setVisible(false);
add(z1);
setSize(dim.width,dim.height);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
z1.setVisible(true);
}
public void create2()
{
add(h1);
z1.setVisible(false);
h1.setVisible(true);
}
public void exe()
{
z1.setVisible(false);
add(z2);
z2.setVisible(true);
79
mythread m= new mythread();
timethread t=new timethread();
m.start();
t.start();
}
public void last()
{
zeroshot2.checkscores();
Fileop.writetofile();
z2.setVisible(false);
add(l1);
l1.setVisible(true);
}
public void highs()
{
l1.setVisible(false);
add(hi);
hi.setVisible(true);
}
}
package mygame;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class htpscreen extends JPanel implements MouseListener
{
Image img=Toolkit.getDefaultToolkit().getImage("C:\\Happy
birds\\ImageFiles\\howtoplayscreen.jpg");
public htpscreen()
{
addMouseListener(this);
}
public void paint(Graphics g)
{
g.drawImage(img,0,0,this);
}
public void mouseClicked(MouseEvent arg0)
{
this.setVisible(false);
zeroshotframe.z1.setVisible(true);
}
public void mousePressed(MouseEvent arg0){}
public void mouseReleased(MouseEvent arg0){}
80
public void mouseEntered(MouseEvent arg0){}
public void mouseExited(MouseEvent arg0){}
}
package mygame;
import java.applet.Applet;
import java.applet.AudioClip;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.*;
public class main extends Applet{
public static zeroshotframe z=new zeroshotframe();
static AudioClip ad;
boolean x=true;
AudioClip song[ ] = new AudioClip[3];
public void init()
{
try
{
File f=new File("C:\\Happy birds\\SystemFiles");
URL url=new URL(f.toURL(),"");
AudioClip ad=getAudioClip(url,"locowav.wav");
z.create1();
while(true)
{
if(x){
ad.loop();
x=false;
}
}
}
catch(MalformedURLException e){}
}
}
package mygame;
import java.awt.Color;
import java.awt.Font;
81
public class timethread extends Thread{
static int mytime=60;
public void run()
{
while(mytime>0){
zeroshot2.time=mytime--;
main.z.z2.repaint();
try {
sleep(1000);
if(mytime%10==0)
zeroshot2.occur=false;
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
zeroshot2.time--;
this.stop();
}
}
package mygame;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
82
public class zeroshot2 extends JPanel implements ActionListener
{
Image bg2=Toolkit.getDefaultToolkit().getImage("C:\\Happy
birds\\ImageFiles\\second2.jpg");
static ImageIcon pig=new ImageIcon("C:\\Happy birds\\ImageFiles\\pig.jpg");
static ImageIcon bird=new ImageIcon("C:\\Happy birds\\ImageFiles\\bird3.jpg");
public int picdis=110;
boolean oncebird=true;
static final int number=30;
static int score=0,time=60;
public int k=1;
static boolean occur=false;
JPanel p1=new JPanel();
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JButton[] object=new JButton[number];
int randomizer=1,previous;
int a;
boolean previcon=false;
static boolean scorechange=false;
public zeroshot2()
{
for(int i=0;i<number;i++)
{
object[i]=new JButton(pig);
object[i].addActionListener(this);
object[i].setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
object[i].setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
object[i].setVisible(false);
}
for(int i=0;i<10;i++)
{
p1.add(object[i]);
p1.add(Box.createRigidArea(new Dimension(picdis,picdis)));
}
for(int i=10;i<20;i++)
{
p2.add(object[i]);
p2.add(Box.createRigidArea(new Dimension(picdis,picdis)));
}
for(int i=20;i<30;i++)
{
p3.add(object[i]);
p3.add(Box.createRigidArea(new Dimension(picdis,picdis)));
83
}
setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
p1.setOpaque(false);
p2.setOpaque(false);
p3.setOpaque(false);
add(Box.createRigidArea(new Dimension(50,150)));
add(p1);
add(p2);
add(p3);
}
public void paintComponent(Graphics g)
{
g.drawImage(bg2,0,0,this);
g.setColor(zeroshotframe.mc);
g.setFont(new Font("Angrybirds",Font.PLAIN,65));
g.drawString(""+score,1205,85);
g.drawString(""+time,155,85);
}
public void setvisible(int x)
{
for(int i=0;i<number;i++)
{
if(i!=x)
{
object[i].setVisible(false);
}
}
if(previcon==true)
{
object[previous].setIcon(pig);
previcon=false;
}
if(occur==false){
a=(int)((Math.random()*100000000)%10);
System.out.println(a);
if(a==1||a==7)
{
object[x].setIcon(bird);
previcon=true;
previous=x;
occur=true;
}
}
object[x].setVisible(true);
84
}
public void actionPerformed(ActionEvent e)
{
if(previcon==true)
{
if(oncebird==true){
if(score>50)
score-=50;
else
score=0;
oncebird=false;
}
}
else
score+=10;
oncebird=true;
repaint();
}
public static void checkscores()
{
for(int i=0;i<3;i++){
if(score>Fileop.scores[i])
{
if(i==0){
Fileop.scores[i+2]=Fileop.scores[i+1];
Fileop.scores[i+1]=Fileop.scores[i];
}
else if(i==1)
{
Fileop.scores[i+1]=Fileop.scores[i];
}
Fileop.scores[i]=score;
scorechange=true;
break;
}
}
}
}
85
OUTPUT:
86
87

You might also like