class ContinueBreak
{
public static void main(String args[])
{
int i,j;
LOOP1:for(i=1;i<=100;i++)
{
System.out.println(" ");
if(i>=10) break;
for(j=1;j<=100;j++);
{
System.out.print(" * ");
if(j==i)
continue LOOP1;
}
}
System.out.println("Termination by BREAK");
}
}
Program to show Common line interface in Java
class ComLineArgs
{
public static void main(String args[])
{
int count,i=0;
String str;
count=args.length;
System.out.println("number of arguments="+count);
while(i<=count)
{
str=args[i];
i++;
System.out.print(i+: "+"java is"+str);
}
}
}
{
public static void main(String args[])
{
int count,i=0;
String str;
count=args.length;
System.out.println("number of arguments="+count);
while(i<=count)
{
str=args[i];
i++;
System.out.print(i+: "+"java is"+str);
}
}
}
Program to show class Casting in Java
class Casting
{
public static void main(String args[])
{
float sum;
int i;
sum=0.0f;
for(i=1;i<=10;i++)
{
sum=sum+1/(float)i;
System.out.print("i="+i);
System.out.println("sum:"+sum);
}
}
}
{
public static void main(String args[])
{
float sum;
int i;
sum=0.0f;
for(i=1;i<=10;i++)
{
sum=sum+1/(float)i;
System.out.print("i="+i);
System.out.println("sum:"+sum);
}
}
}
Creating Application Server in Java
//import classes
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.awt.*;
//Code for the AppServer class
class MyFrame extends Frame implements ActionListener
{
MyFrame()
{
setSize(600,400);
setVisible(true);
this.setTitle("Welcome to server");
JPanel panel=new JPanel();
//panel.setBackground(new Color(0,100,100));
setLayout(new FlowLayout());
JButton btnReport;
JButton btnExit;
btnReport=new JButton("Report");
panel.add(btnReport);
btnExit=new JButton("Exit");
panel.add(btnExit);
add(panel);
btnReport.addActionListener(this);
btnExit.addActionListener(this);
setVisible(true);//add listener to the Login button
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand();
if(str.equals("Report"))
{
new Reportjen();
}
else if(str.equals("Exit"))
{
System.exit(0);
}
}
}
public class AppServer implements Runnable
{
ServerSocket server;
Socket fromClient;
Thread serverThread;
InetAddress host;
public AppServer()
{
MyFrame obj=new MyFrame();
System.out.println("Conference Engine started...");
try
{
host = InetAddress.getLocalHost();
System.out.println("Host name:'" + host.getHostName()
+ "' has IP address: " + host.getHostAddress());
server = new ServerSocket(1001);
serverThread = new Thread(this);
serverThread.start();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch(Exception e)
{
System.out.println("Cannot start the thread: " + e);
}
}
public static void main(String args[])
{
new AppServer();
}
public void run()
{
try
{
while(true)
{
//Listening to the clients request
fromClient = server.accept();
//Creating the connect object
Connect con = new Connect(fromClient);
}
}
catch(Exception e)
{
System.out.println("Cannot listen to the client" + e);
}
}
}
//Code for the connect class
class Connect
{
ObjectOutputStream streamToClient;
int ctr=0;
BufferedReader streamFromClient;
static Vector vector;
static Vector vctrList;
String message=" ";
static String str=new String("UsrList");
static
{
vector=new Vector(1,1);
vctrList=new Vector(1,1);
vctrList.addElement((String)str);
}
int verify(String mesg)
{
try
{
RandomAccessFile RAS=new RandomAccessFile("UsrPwd.txt", "r");
int i=0;
String str="";
while((RAS.getFilePointer())!=(RAS.length()))
{
str=RAS.readLine();
if(str.equals(mesg))
{
ctr=1;
break;
}
}
RAS.close();
}
catch(Exception e)
{
}
return ctr;
}//end of verify()
int checkFile(String mesg)
{
int chk=1;
try
{
RandomAccessFile RS=new RandomAccessFile("UsrPwd.txt", "r");
int i=0;
String str="";
String colon=new String(":");
int index=((String)mesg).lastIndexOf(colon);
String userName=(String)mesg.substring(0,index);
while((RS.getFilePointer())!=(int)(RS.length()))
{
str=RS.readLine();
int index1=((String)str).lastIndexOf(colon);
String usrName=(String)str.substring(0,index1);
if(usrName.equals(userName))
{
chk=0;
break;
}
}//end of while
RS.close();
}//end of try
catch(Exception e)
{
}
return chk;
}//end of chkFile
public Connect(Socket inFromClient)
{
//Retrieving the clients stream
String msg="",msg1="";
String mesg="";
try
{
streamFromClient = new BufferedReader(new InputStreamReader(inFromClient.getInputStream()));
streamToClient= new ObjectOutputStream(inFromClient.getOutputStream());
msg=streamFromClient.readLine();
//mesg=streamFromClient.readLine();
if((msg.equals("From Timer")))
{
streamToClient.writeObject(vector);
streamToClient.writeObject(vctrList);
}
else if(msg.equals("LoginInfo"))
{ System.out.println(inFromClient.getInetAddress());
msg=streamFromClient.readLine();
int ver=verify(msg);
if(ver==1)
{
msg1=streamFromClient.readLine();
FileOutputStream out = new FileOutputStream("Loginfo.txt",true);
PrintStream p = new PrintStream( out );
p.println();
p.println(msg1);
p.close();
String colon=new String(":");
int index=((String)msg).lastIndexOf(colon);
String userName=(String)msg.substring(0,index) +inFromClient.getInetAddress();
if(!(vctrList.indexOf((String)userName)>0))
{
streamToClient.writeObject("Welcome"+inFromClient.getInetAddress());
vctrList.addElement((String)userName);
}
}
else
{
streamToClient.writeObject("Login denied");
}
}
else if(msg.equals("RegisterInfo"))
{
msg=streamFromClient.readLine();
int ret=checkFile(msg);
if(ret==0)
streamToClient.writeObject("User Exists");
if(ret==1)
{
FileOutputStream out = new FileOutputStream("UsrPwd.txt",true);
PrintStream p = new PrintStream( out );
p.println();
p.println(msg);
p.close();
streamToClient.writeObject("Registered");
}
}
else if(msg.equals("User Logout"))
{
String remUser=streamFromClient.readLine();
boolean b=vctrList.removeElement((String)remUser);
}
else
{
message=message+msg;
vector.addElement((String)message);
streamToClient.writeObject(vector);
}
}//end of try
catch(Exception e)
{
System.out.println("Cannot get the client stream connect" + e);
}
finally
{
try
{
inFromClient.close();
}
catch(IOException e)
{}
}
}//end of connect
}
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.awt.*;
//Code for the AppServer class
class MyFrame extends Frame implements ActionListener
{
MyFrame()
{
setSize(600,400);
setVisible(true);
this.setTitle("Welcome to server");
JPanel panel=new JPanel();
//panel.setBackground(new Color(0,100,100));
setLayout(new FlowLayout());
JButton btnReport;
JButton btnExit;
btnReport=new JButton("Report");
panel.add(btnReport);
btnExit=new JButton("Exit");
panel.add(btnExit);
add(panel);
btnReport.addActionListener(this);
btnExit.addActionListener(this);
setVisible(true);//add listener to the Login button
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand();
if(str.equals("Report"))
{
new Reportjen();
}
else if(str.equals("Exit"))
{
System.exit(0);
}
}
}
public class AppServer implements Runnable
{
ServerSocket server;
Socket fromClient;
Thread serverThread;
InetAddress host;
public AppServer()
{
MyFrame obj=new MyFrame();
System.out.println("Conference Engine started...");
try
{
host = InetAddress.getLocalHost();
System.out.println("Host name:'" + host.getHostName()
+ "' has IP address: " + host.getHostAddress());
server = new ServerSocket(1001);
serverThread = new Thread(this);
serverThread.start();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch(Exception e)
{
System.out.println("Cannot start the thread: " + e);
}
}
public static void main(String args[])
{
new AppServer();
}
public void run()
{
try
{
while(true)
{
//Listening to the clients request
fromClient = server.accept();
//Creating the connect object
Connect con = new Connect(fromClient);
}
}
catch(Exception e)
{
System.out.println("Cannot listen to the client" + e);
}
}
}
//Code for the connect class
class Connect
{
ObjectOutputStream streamToClient;
int ctr=0;
BufferedReader streamFromClient;
static Vector vector;
static Vector vctrList;
String message=" ";
static String str=new String("UsrList");
static
{
vector=new Vector(1,1);
vctrList=new Vector(1,1);
vctrList.addElement((String)str);
}
int verify(String mesg)
{
try
{
RandomAccessFile RAS=new RandomAccessFile("UsrPwd.txt", "r");
int i=0;
String str="";
while((RAS.getFilePointer())!=(RAS.length()))
{
str=RAS.readLine();
if(str.equals(mesg))
{
ctr=1;
break;
}
}
RAS.close();
}
catch(Exception e)
{
}
return ctr;
}//end of verify()
int checkFile(String mesg)
{
int chk=1;
try
{
RandomAccessFile RS=new RandomAccessFile("UsrPwd.txt", "r");
int i=0;
String str="";
String colon=new String(":");
int index=((String)mesg).lastIndexOf(colon);
String userName=(String)mesg.substring(0,index);
while((RS.getFilePointer())!=(int)(RS.length()))
{
str=RS.readLine();
int index1=((String)str).lastIndexOf(colon);
String usrName=(String)str.substring(0,index1);
if(usrName.equals(userName))
{
chk=0;
break;
}
}//end of while
RS.close();
}//end of try
catch(Exception e)
{
}
return chk;
}//end of chkFile
public Connect(Socket inFromClient)
{
//Retrieving the clients stream
String msg="",msg1="";
String mesg="";
try
{
streamFromClient = new BufferedReader(new InputStreamReader(inFromClient.getInputStream()));
streamToClient= new ObjectOutputStream(inFromClient.getOutputStream());
msg=streamFromClient.readLine();
//mesg=streamFromClient.readLine();
if((msg.equals("From Timer")))
{
streamToClient.writeObject(vector);
streamToClient.writeObject(vctrList);
}
else if(msg.equals("LoginInfo"))
{ System.out.println(inFromClient.getInetAddress());
msg=streamFromClient.readLine();
int ver=verify(msg);
if(ver==1)
{
msg1=streamFromClient.readLine();
FileOutputStream out = new FileOutputStream("Loginfo.txt",true);
PrintStream p = new PrintStream( out );
p.println();
p.println(msg1);
p.close();
String colon=new String(":");
int index=((String)msg).lastIndexOf(colon);
String userName=(String)msg.substring(0,index) +inFromClient.getInetAddress();
if(!(vctrList.indexOf((String)userName)>0))
{
streamToClient.writeObject("Welcome"+inFromClient.getInetAddress());
vctrList.addElement((String)userName);
}
}
else
{
streamToClient.writeObject("Login denied");
}
}
else if(msg.equals("RegisterInfo"))
{
msg=streamFromClient.readLine();
int ret=checkFile(msg);
if(ret==0)
streamToClient.writeObject("User Exists");
if(ret==1)
{
FileOutputStream out = new FileOutputStream("UsrPwd.txt",true);
PrintStream p = new PrintStream( out );
p.println();
p.println(msg);
p.close();
streamToClient.writeObject("Registered");
}
}
else if(msg.equals("User Logout"))
{
String remUser=streamFromClient.readLine();
boolean b=vctrList.removeElement((String)remUser);
}
else
{
message=message+msg;
vector.addElement((String)message);
streamToClient.writeObject(vector);
}
}//end of try
catch(Exception e)
{
System.out.println("Cannot get the client stream connect" + e);
}
finally
{
try
{
inFromClient.close();
}
catch(IOException e)
{}
}
}//end of connect
}
Program to find area of Rectangle in java
abstract class Figure
{
double dim1;
double dim2;
Figure(double a, double b)
{
dim1=a;
dim2=b;
}
abstract double area();
}
class Rectangle extends Figure
{
Rectangle(double a, double b)
{
super(a,b);
}
double area()
{
System.out.println("Area of Rectangle");
return(dim1*dim2);
}
}
class Triangle extends Figure
{
Triangle(double a, double b)
{
super(a,b);
}
double area()
{
System.out.println("area of triangle");
return(dim1*dim2/2);
}
}
class AbstractArea
{
public static void main(String args[])
{
Rectangle r=new Rectangle(10,5);
Triangle t=new Triangle(10,2);
Figure figref;
figref=r;
double d1=figref.area();
System.out.println(d1);
figref=t;
double d2=figref.area();
System.out.println(d2);
}
}
{
double dim1;
double dim2;
Figure(double a, double b)
{
dim1=a;
dim2=b;
}
abstract double area();
}
class Rectangle extends Figure
{
Rectangle(double a, double b)
{
super(a,b);
}
double area()
{
System.out.println("Area of Rectangle");
return(dim1*dim2);
}
}
class Triangle extends Figure
{
Triangle(double a, double b)
{
super(a,b);
}
double area()
{
System.out.println("area of triangle");
return(dim1*dim2/2);
}
}
class AbstractArea
{
public static void main(String args[])
{
Rectangle r=new Rectangle(10,5);
Triangle t=new Triangle(10,2);
Figure figref;
figref=r;
double d1=figref.area();
System.out.println(d1);
figref=t;
double d2=figref.area();
System.out.println(d2);
}
}
Creating circle in java
interface NewShape
{
//void draw();
}
interface Circle extends NewShape
{
void getRadius();
int radius=10;
}
class NewCircle implements Circle
{
public void getRadius()
{
System.out.println(radius);
}
}
class ExtendInterface extends NewCircle
{
public static void main(String args[])
{
Circle nc=new NewCircle();
nc.getRadius();
}
}
{
//void draw();
}
interface Circle extends NewShape
{
void getRadius();
int radius=10;
}
class NewCircle implements Circle
{
public void getRadius()
{
System.out.println(radius);
}
}
class ExtendInterface extends NewCircle
{
public static void main(String args[])
{
Circle nc=new NewCircle();
nc.getRadius();
}
}
Error handling in java catch throw.
class Error1
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=5;
int x,y;
try
{
x=a/(b-c);
}
catch(ArithmeticException e)
{
System.out.println("Division by zero");
}
y=a/(b+c);
System.out.println("Result="+y);
}
}
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=5;
int x,y;
try
{
x=a/(b-c);
}
catch(ArithmeticException e)
{
System.out.println("Division by zero");
}
y=a/(b+c);
System.out.println("Result="+y);
}
}
Bank project of simple intrest in java.
interface account
{
float rate=8.5f;
void set(int accno);
void display();
}
interface person
{
void store(String name, String address);
void show();
}
class Customer implements account, person
{
int accno, numyears;
float bal;
String name="";
String address="";
Customer(float a, int b)
{
bal=a;
numyears=b;
}
public void set(int accno)
{
this.accno=accno;
}
public void display()
{
System.out.println("the account no. and balance is: "+accno+bal);
}
public void store(String name, String address)
{
this.name=name;
this.address=address;
}
public void show()
{
System.out.println("the name and the address is:"+name+" "+address);
}
void interest()
{
float si=bal*numyears*rate/100;
System.out.println("the simple interest is:"+si);
}
}
class Details
{
public static void main(String args[])
{
Customer c1=new Customer(15.0f, 2);
c1.set(100);
c1.store("Popsys","nagpur");
c1.show();
c1.display();
c1.interest();
}
}
File operation in java
import java.io.*;
class CopyFile
{
public static void main(String args[])
{
FileInputStream A=null;
FileOutputStream B=null;
int b;
try
{
A=new FileInputStream("a.txt");
B = new FileOutputStream("b.txt");
while((b=A.read())!=-1)
{
B.write(b);
}
A.close();
B.close();
System.out.println("File copied successfully");
}
catch(IOException e)
{
System.out.println("file not found");
}
}
}
class CopyFile
{
public static void main(String args[])
{
FileInputStream A=null;
FileOutputStream B=null;
int b;
try
{
A=new FileInputStream("a.txt");
B = new FileOutputStream("b.txt");
while((b=A.read())!=-1)
{
B.write(b);
}
A.close();
B.close();
System.out.println("File copied successfully");
}
catch(IOException e)
{
System.out.println("file not found");
}
}
}
Creating pyramid of asterisk in java
class ContinueBreak
{
public static void main(String args[])
{
int i,j;
LOOP1:for(i=1;i<=100;i++)
{
System.out.println(" ");
if(i>=10)
break;
for(j=1;j<=100;j++);
{
System.out.print(" * ");
if(j==i)
continue LOOP1;
}
}
System.out.println("Termination by BREAK");
}
}
While loop in Java
class ComLineArgs
{
public static void main(String args[])
{
int count,i=0;
String str;
count=args.length;
System.out.println("number of arguments="+count);
while(i<=count)
{
str=args[i];
i++;
System.out.print(i+: "+"java is"+str);
}
}
}
Creating | drawing circle in Java
interface NewShape
{
void draw();
}
class NewCircle1 implements NewShape
{
public void draw()
{
System.out.println("new circle 1 is drawn");
}
}
class NewCircle2
{
public void draw()
{
System.out.println("new cirlce 2 is drawn");
}
}
class CastInterface
{
public static void main(String args[])
{
NewShape nc1=new NewCircle1();
NewCircle2 nc2=new NewCircle2();
nc1.draw();
nc2.draw();
}
}
Creating class in Java.
class A
{
void show()
{
System.out.println("method of class A");
}
}
class B extends A
{
void show()
{
System.out.println("method of class b");
}
}
class C extends A
{
void show()
{
System.out.println("method of class c");
}
}
class MethodDispath
{
public static void main(String args[])
{
class A a=new A();
class B b=new B();
class A c=new C();
A aa;
aa=a;
aa.show();
aa.b;
aa.show();
aa=c;
aa.show();
}
}
Abstract Demo Program in Java
abstract class classA
{
abstract void show();
void display()
{
System.out.println("this is a concrete method");
}
}
class classB extends classA
{
void show()
{
System.out.println("classb implementation of show method");
}
}
class AbstractDemo
{
public static void main(String args[])
{
classB b1=new classB();
b1.show();
b1.display();
}
}
Program to calculate Area of Rectangle in java
abstract class Figure
{
double dim1;
double dim2;
Figure(double a, double b)
{
dim1=a;
dim2=b;
}
abstract double area();
}
class Rectangle extends Figure
{
Rectangle(double a, double b)
{
super(a,b);
}
double area()
{
System.out.println("Area of Rectangle");
return(dim1*dim2);
}
}
class Triangle extends Figure
{
Triangle(double a, double b)
{
super(a,b);
}
double area()
{
System.out.println("area of triangle");
return(dim1*dim2/2);
}
}
class AbstractArea
{
public static void main(String args[])
{
Rectangle r=new Rectangle(10,5);
Triangle t=new Triangle(10,2);
Figure figref;
figref=r;
double d1=figref.area();
System.out.println(d1);
figref=t;
double d2=figref.area();
System.out.println(d2);
}
}
Java applet program for interest rate calculation
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
*/
public class Loan extends Applet
implements ActionListener,ItemListener
{
double p,r,n,total,i;
String param1;
boolean month;
Label l1,l2,l3,l4;
TextField t1,t2,t3,t4;
Button b1,b2;
CheckboxGroup cbg;
Checkbox c1,c2;
String str;
public void init()
{
l1=new Label("Balance Amount",Label.LEFT);
l2=new Label("Number of Months",Label.LEFT);
l3=new Label("Interest Rate",Label.LEFT);
l4=new Label("Total Payment",Label.LEFT);
t1=new TextField(5);
t2=new TextField(5);
t3=new TextField(15);
t4=new TextField(20);
b1=new Button("OK");
b2=new Button("Delete");
cbg=new CheckboxGroup();
c1=new Checkbox("Month Rate",cbg,true);
c2=new Checkbox("Annual Rate",cbg,true);
t1.addActionListener(this);
t2.addActionListener(this);
t3.addActionListener(this);
t4.addActionListener(this);
b1.addActionListener(this);
b2.addActionListener(this);
c1.addItemListener(this);
c2.addItemListener(this);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(l4);
add(t4);
add(c1);
add(c2);
add(b1);
add(b2);
}
public void itemStateChanged(ItemEvent ie)
{
}
public void actionPerformed(ActionEvent ae)
{
str=ae.getActionCommand();
if(str.equals("OK"))
{
p=Double.parseDouble(t1.getText());
n=Double.parseDouble(t2.getText());
r=Double.parseDouble(t3.getText());
if(c2.getState())
{
n=n/12;
}
i=(p*n*r)/100;
total=p+i;
t4.setText(" "+total);
}
else if(str.equals("Delete"))
{
t1.setText(" ");
t2.setText(" ");
t3.setText(" ");
t4.setText(" ");
}
}
}
Java applet program that allows the user to draw lines, rectangles and ovals
Color c1=new Color(35-i,55-i,110-i);
g.setColor(c1);
g.drawRect(250+i,250+i,100+i,100+i);
g.drawOval(100+i,100+i,50+i,50+i);
g.drawLine(50+i,20+i,10+i,10+i);
g.setColor(c1);
g.drawRect(250+i,250+i,100+i,100+i);
g.drawOval(100+i,100+i,50+i,50+i);
g.drawLine(50+i,20+i,10+i,10+i);
Java program to implement a shape selector from a given set of shapes by Ranjith | April 4th, 2010. To implement a shape selector from a given set o
import java.awt*;
import java.awt.event.*;
import java.applet.*;
public class fillcolor extends Applet implement Item Listener
{
checkbox red,yellow,black,blue.orange;
CheckboxGroup cbg;
String msg;
String s1="red";
String s2="yellow";
String s3="black";
String s4="orange";
public void init()
{
cbg = new CheckboxGroup();
red = new Chechbox("red",cbg,true);
yellow= new Checkbox("yellow",cbg,false);
black = new checkbox("black",cbg,false);
blue = new Checkbox("blue",cbg,false);
orange = new checkbox("orange".cbg.false);
add(red);
add(yellow);
add(black);
add(blue);
add(orange);
red.addItemListener(this);
yellow.addItemListener(this);
black.addItemListener(this);
blue.addItemListener(this);
orange.addItemListener(this);
}
publice void itemStartechanged(ItemEvent ie)
{
repaint();
}
publice void paint (Graphics g)
{
msg = cbg.getSelectedCheckbox().getLabel();
if(msg.compareTo(s1)==0)
{
setBackground(Color.red);
}
else if (msg.compareTo(s2)==0)
{
setBackground(Color.yellow);
}
else if(msg.compare To(s3)==0)
{
setBackground(color.black);
}
else if (msg.compareTo(s4)==o)
{
setBackground(Color.blue);
}
else
{
set Background(Color.orange);
}
}
}
import java.awt.event.*;
import java.applet.*;
public class fillcolor extends Applet implement Item Listener
{
checkbox red,yellow,black,blue.orange;
CheckboxGroup cbg;
String msg;
String s1="red";
String s2="yellow";
String s3="black";
String s4="orange";
public void init()
{
cbg = new CheckboxGroup();
red = new Chechbox("red",cbg,true);
yellow= new Checkbox("yellow",cbg,false);
black = new checkbox("black",cbg,false);
blue = new Checkbox("blue",cbg,false);
orange = new checkbox("orange".cbg.false);
add(red);
add(yellow);
add(black);
add(blue);
add(orange);
red.addItemListener(this);
yellow.addItemListener(this);
black.addItemListener(this);
blue.addItemListener(this);
orange.addItemListener(this);
}
publice void itemStartechanged(ItemEvent ie)
{
repaint();
}
publice void paint (Graphics g)
{
msg = cbg.getSelectedCheckbox().getLabel();
if(msg.compareTo(s1)==0)
{
setBackground(Color.red);
}
else if (msg.compareTo(s2)==0)
{
setBackground(Color.yellow);
}
else if(msg.compare To(s3)==0)
{
setBackground(color.black);
}
else if (msg.compareTo(s4)==o)
{
setBackground(Color.blue);
}
else
{
set Background(Color.orange);
}
}
}
Java program to implement a shape selector from a given set of shapes
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class shape extend Applet implements itemListener
{
Chekbox reet,circle,line;
ChekboxGroup cbg;
String msg;
String s1="reet";
String s2="circle";
string s3="line";
publice void init()
{
cbg=new checkboxGroup();
rect = new checkbox("reet,cbg,tru);
circle = new Checkbox("circle",cbg.false);
line = new Checkbox("line",cbg,false);
add(reet);
add(circle);
add(line);
rect.addItemListener(this);
circle.addItemLisener(this);
line.addItemListener(this);
}
public void item StateChanged(ItemEvent ie)
{
repaint();
}
publice void paint(Graphics g)
{
msg=cbg.getSlectedCheckbox().getLabel();
if(masg.compareTo(s1)==0)
{
g.drawRect(10,40,40,80);
}
else if(msg.compareTo(s2)==0)
{
g.drawOvel(10,40,80,80);
}
else
{
g.drawLine(0,0,100,100);
}
}
}
import java.awt.event.*;
import java.applet.*;
public class shape extend Applet implements itemListener
{
Chekbox reet,circle,line;
ChekboxGroup cbg;
String msg;
String s1="reet";
String s2="circle";
string s3="line";
publice void init()
{
cbg=new checkboxGroup();
rect = new checkbox("reet,cbg,tru);
circle = new Checkbox("circle",cbg.false);
line = new Checkbox("line",cbg,false);
add(reet);
add(circle);
add(line);
rect.addItemListener(this);
circle.addItemLisener(this);
line.addItemListener(this);
}
public void item StateChanged(ItemEvent ie)
{
repaint();
}
publice void paint(Graphics g)
{
msg=cbg.getSlectedCheckbox().getLabel();
if(masg.compareTo(s1)==0)
{
g.drawRect(10,40,40,80);
}
else if(msg.compareTo(s2)==0)
{
g.drawOvel(10,40,80,80);
}
else
{
g.drawLine(0,0,100,100);
}
}
}
Java program that illustrates how run time polymorphism is achieved
figure f=new figure(45,6);
rectangle r=new rectangle(10,30);
triangle t=new triangle(10,20);
figure a;
a=f;
System.out.println(a.area());
rectangle r=new rectangle(10,30);
triangle t=new triangle(10,20);
figure a;
a=f;
System.out.println(a.area());
Java Program for calculator
JPanel p = new JPanel();
p.setLayout(new GridLayout(4, 4));
String buttons = “789/456*123-0.=+”;
for (int i = 0; i < buttons.length(); i++)
addButton(p, buttons.substring(i, i + 1));
add(p, “Center”);
p.setLayout(new GridLayout(4, 4));
String buttons = “789/456*123-0.=+”;
for (int i = 0; i < buttons.length(); i++)
addButton(p, buttons.substring(i, i + 1));
add(p, “Center”);
Java program to display a clock
background_ = new GSegment();
GStyle backgroundStyle = new GStyle();
backgroundStyle.setBackgroundColor (new Color (122, 136, 161));
backgroundStyle.setForegroundColor (new Color (0, 0, 0));
background_.setStyle (backgroundStyle);
addSegment (background_);
GStyle backgroundStyle = new GStyle();
backgroundStyle.setBackgroundColor (new Color (122, 136, 161));
backgroundStyle.setForegroundColor (new Color (0, 0, 0));
background_.setStyle (backgroundStyle);
addSegment (background_);
Java program to display Local machines IP Address
import java.net.*;
import java.io.*;
public class ip_localmachine
{
public static void main(String args[]) throws Exception
{
InetAddress ipadd =InetAddress.getLocalHost();
System.out.println("Host and Address :"+ipadd);
System.out.println("Host name :"+ipadd.getHostName());
String n=ipadd.toString();
System.out.println("IP address :"+n.substring(n.indexOf("/")+1));
}
}
import java.io.*;
public class ip_localmachine
{
public static void main(String args[]) throws Exception
{
InetAddress ipadd =InetAddress.getLocalHost();
System.out.println("Host and Address :"+ipadd);
System.out.println("Host name :"+ipadd.getHostName());
String n=ipadd.toString();
System.out.println("IP address :"+n.substring(n.indexOf("/")+1));
}
}
Java program that checks whether the given string is palindrome or not
StringBuffer s1=new StringBuffer(args[0]);
StringBuffer s2=new StringBuffer(s1);
s1.reverse();
System.out.println(“Given String is:”+s2);
System.out.println(“Reverse String is”+s1);
Read More..
StringBuffer s2=new StringBuffer(s1);
s1.reverse();
System.out.println(“Given String is:”+s2);
System.out.println(“Reverse String is”+s1);
Read More..
Java Program to multiply two matrices
for(int j=i+1;j
{
if(names[i].compareTo(names[j])<0)
{
temp=names[i];
names[i]=names[j];
names[j]=temp;
}
}
{
if(names[i].compareTo(names[j])<0)
{
temp=names[i];
names[i]=names[j];
names[j]=temp;
}
}
Java program that displays the number of characters, lines and words in a text file
while((c=isr.read())!=-1)
{
chars++;
if(c==’\n’)
lines++;
if(c==’\t’ || c==’ ‘ || c==’\n’)
++words;
if(chars!=0)
++chars;
}
{
chars++;
if(c==’\n’)
lines++;
if(c==’\t’ || c==’ ‘ || c==’\n’)
++words;
if(chars!=0)
++chars;
}
Java program to display Domain name service (DNS)
import java.net.*;
class dns
{
public static void main(String args[]) throws Exception
{
try
{
InetAddress[] address=InetAddress.getAllByName("java.sun.com");
for(int j=0;j System.out.println(address[j]);
}
catch(Exception e)
{
System.out.println("Error in accessing Internet :"+e);
}
}
}
class dns
{
public static void main(String args[]) throws Exception
{
try
{
InetAddress[] address=InetAddress.getAllByName("java.sun.com");
for(int j=0;j
}
catch(Exception e)
{
System.out.println("Error in accessing Internet :"+e);
}
}
}
Bitwise Operators in java
class BitwiseOperators2 {
public static void main(String args[]) {
short s = 0xff;
System.out.println(s);
System.out.println(s & 0xf);
System.out.println(s | 1);
System.out.println(s ^ 1);
System.out.println(~s);
System.out.println(s >> 2);
System.out.println(s >>> 2);
System.out.println(s << 2);
}
}
public static void main(String args[]) {
short s = 0xff;
System.out.println(s);
System.out.println(s & 0xf);
System.out.println(s | 1);
System.out.println(s ^ 1);
System.out.println(~s);
System.out.println(s >> 2);
System.out.println(s >>> 2);
System.out.println(s << 2);
}
}
Deadlock Demo in java
class A
{
B b;
synchronized void a1()
{
System.out.println("Starting a1");
b.b2();
}
synchronized void a2()
{
System.out.println("Starting a2");
}
}
class B
{
A a;
synchronized void b1() {
System.out.println("Starting b1");
a.a2();
}
synchronized void b2() {
System.out.println("Starting b2");
}
}
class Thread1 extends Thread {
A a;
Thread1(A a) {
this.a = a;
}
public void run() {
for(int i = 0; i <>
a.a1();
}
}
class Thread2 extends Thread {
B b;
Thread2(B b) {
this.b = b;
}
public void run() {
for(int i = 0; i <>
b.b1();
}
}
class DeadlockDemo {
public static void main(String args[]) {
// Create objects
A a = new A();
B b = new B();
a.b = b;
b.a = a;
// Create threads
Thread1 t1 = new Thread1(a);
Thread2 t2 = new Thread2(b);
t1.start();
t2.start();
// Wait for threads to complete
try {
t1.join();
t2.join();
}
catch(Exception e) {
e.printStackTrace();
}
// Display message
System.out.println("Done!");
}
}
{
B b;
synchronized void a1()
{
System.out.println("Starting a1");
b.b2();
}
synchronized void a2()
{
System.out.println("Starting a2");
}
}
class B
{
A a;
synchronized void b1() {
System.out.println("Starting b1");
a.a2();
}
synchronized void b2() {
System.out.println("Starting b2");
}
}
class Thread1 extends Thread {
A a;
Thread1(A a) {
this.a = a;
}
public void run() {
for(int i = 0; i <>
a.a1();
}
}
class Thread2 extends Thread {
B b;
Thread2(B b) {
this.b = b;
}
public void run() {
for(int i = 0; i <>
b.b1();
}
}
class DeadlockDemo {
public static void main(String args[]) {
// Create objects
A a = new A();
B b = new B();
a.b = b;
b.a = a;
// Create threads
Thread1 t1 = new Thread1(a);
Thread2 t2 = new Thread2(b);
t1.start();
t2.start();
// Wait for threads to complete
try {
t1.join();
t2.join();
}
catch(Exception e) {
e.printStackTrace();
}
// Display message
System.out.println("Done!");
}
}
Project of Bank Demo in java
class Account2 {
private int balance;
void deposit(int amount) {
synchronized(this) {
balance += amount;
}
}
int getBalance() {
return balance;
}
}
class Customer2 extends Thread {
Account2 account;
Customer2(Account2 account) {
this.account = account;
}
public void run() {
try {
for(int i = 0; i <>
account.deposit(10);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
class BankDemo2 {
private final static int NUMCUSTOMERS = 10;
public static void main(String args[]) {
// Create account
Account2 account = new Account2();
// Create and start customer threads
Customer2 customers[] = new Customer2[NUMCUSTOMERS];
for(int i = 0; i <>
customers[i] = new Customer2(account);
customers[i].start();
}
// Wait for customer threads to complete
for(int i = 0; i <>
try {
customers[i].join();
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
// Display account balance
System.out.println(account.getBalance());
}
}
private int balance;
void deposit(int amount) {
synchronized(this) {
balance += amount;
}
}
int getBalance() {
return balance;
}
}
class Customer2 extends Thread {
Account2 account;
Customer2(Account2 account) {
this.account = account;
}
public void run() {
try {
for(int i = 0; i <>
account.deposit(10);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
class BankDemo2 {
private final static int NUMCUSTOMERS = 10;
public static void main(String args[]) {
// Create account
Account2 account = new Account2();
// Create and start customer threads
Customer2 customers[] = new Customer2[NUMCUSTOMERS];
for(int i = 0; i <>
customers[i] = new Customer2(account);
customers[i].start();
}
// Wait for customer threads to complete
for(int i = 0; i <>
try {
customers[i].join();
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
// Display account balance
System.out.println(account.getBalance());
}
}
Standard and Scientific Calculator In Java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class calculator extends JFrame implements ActionListener
{
JTextField jtx;
double temp,temp1,result,a;
static double m1,m2;
int k=1,x=0,y=0,z=0;
char ch;
JButton
one,two,three,four,five,six,seven,eight,nine,zero,clr,pow2,pow3,exp;
JButton
plus,min,div,lg,rec,mul,eq,plmi,poin,mr,mc,mp,mm,sqrt,sin,cos,tan;
JMenuBar bar;
JMenu view;
JMenuItem exit;
JRadioButtonMenuItem standard,scientific;
JSeparator jp;
ButtonGroup bg;
Container cont;
JPanel textPanel,syntpanel,buttonpanel;
calculator()
{
cont=getContentPane();
cont.setLayout(new BorderLayout());
JPanel textpanel=new JPanel();
Font font=new Font("Arial",Font.PLAIN,18);
jtx=new JTextField(25);
jtx.setFont(font);
jtx.setHorizontalAlignment(SwingConstants.RIGHT);
jtx.addKeyListener(new KeyAdapter()
{
public void keyTyped(KeyEvent keyevent)
{
char c=keyevent.getKeyChar();
if(c>='0' && c<='9')
{
}
else
{
keyevent.consume();
}
}
});
textpanel.add(jtx);
buttonpanel=new JPanel();
buttonpanel.setLayout(new GridLayout(5,4,2,2));
boolean t=true;
syntpanel=new JPanel();
syntpanel.setLayout(new GridLayout(5,1));
bar=new JMenuBar();
view=new JMenu("View");
standard =new JRadioButtonMenuItem("Standard",true);
standard.setMnemonic('S');
standard.addItemListener(new radiohandler());
scientific =new JRadioButtonMenuItem("Sceintific");
standard.setMnemonic('c');
scientific.addItemListener(new radiohandler());
jp=new JSeparator();
exit=new JMenuItem("Exit");
standard.setMnemonic('E');
exit.addActionListener(this);
bg=new ButtonGroup();
bg.add(standard);
bg.add(scientific);
view.add(standard);
view.add(scientific);
view.add(jp);
view.add(exit);
bar.add(view);
setJMenuBar(bar);
mr=new JButton("MR");
buttonpanel.add(mr);
mr.addActionListener(this);
seven=new JButton("7");
buttonpanel.add(seven);
seven.addActionListener(this);
eight=new JButton("8");
buttonpanel.add(eight);
eight.addActionListener(this);
nine=new JButton("9");
buttonpanel.add(nine);
nine.addActionListener(this);
clr=new JButton("AC");
buttonpanel.add(clr);
clr.addActionListener(this);
mc=new JButton("MC");
buttonpanel.add(mc);
mc.addActionListener(this);
four=new JButton("4");
buttonpanel.add(four);
four.addActionListener(this);
five=new JButton("5");
buttonpanel.add(five);
five.addActionListener(this);
six=new JButton("6");
buttonpanel.add(six);
six.addActionListener(this);
mul=new JButton("*");
buttonpanel.add(mul);
mul.addActionListener(this);
mp=new JButton("M+");
buttonpanel.add(mp);
mp.addActionListener(this);
one=new JButton("1");
buttonpanel.add(one);
one.addActionListener(this);
two=new JButton("2");
buttonpanel.add(two);
two.addActionListener(this);
three=new JButton("3");
buttonpanel.add(three);
three.addActionListener(this);
min=new JButton("-");
buttonpanel.add(min);
min.addActionListener(this);
mm=new JButton("M-");
buttonpanel.add(mm);
mm.addActionListener(this);
zero=new JButton("0");
buttonpanel.add(zero);
zero.addActionListener(this);
plmi=new JButton("+/-");
buttonpanel.add(plmi);
plmi.addActionListener(this);
poin=new JButton(".");
buttonpanel.add(poin);
poin.addActionListener(this);
plus=new JButton("+");
buttonpanel.add(plus);
plus.addActionListener(this);
rec=new JButton("1/x");
buttonpanel.add(rec);
rec.addActionListener(this);
sqrt=new JButton("Sqrt");
buttonpanel.add(sqrt);
sqrt.addActionListener(this);
lg=new JButton("log");
buttonpanel.add(lg);
lg.addActionListener(this);
div=new JButton("/");
div.addActionListener(this);
buttonpanel.add(div);
eq=new JButton("=");
buttonpanel.add(eq);
eq.addActionListener(this);
sin=new JButton("SIN");
syntpanel.add(sin);
sin.addActionListener(this);
cos=new JButton("COS");
syntpanel.add(cos);
cos.addActionListener(this);
tan=new JButton("TAN");
syntpanel.add(tan);
tan.addActionListener(this);
pow2=new JButton("x^2");
syntpanel.add(pow2);
pow2.addActionListener(this);
pow3=new JButton("x^3");
syntpanel.add(pow3);
pow3.addActionListener(this);
exp=new JButton("Exp");
exp.addActionListener(this);
cont.add("Center",buttonpanel);
cont.add("North",textpanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class radiohandler implements ItemListener
{
public void itemStateChanged(ItemEvent ie)
{
AbstractButton button=(AbstractButton)ie.getItem();
String label=button.getText();
{
if(label.equals("Standard"))
{
cont.remove(syntpanel);
validate();
}
if(label.equals("Sceintific"))
{
cont.add("West",syntpanel);
validate();
}
}
}
}
public void actionPerformed(ActionEvent e)
{
String s=e.getActionCommand();
if(s.equals("Exit"))
{
System.exit(0);
}
if(s.equals("1"))
{
if(z==0)
{
jtx.setText(jtx.getText()+"1");
}
else
{
jtx.setText("");
jtx.setText(jtx.getText()+"1");
z=0;
}
}
if(s.equals("2"))
{
if(z==0)
{
jtx.setText(jtx.getText()+"2");
}
else
{
jtx.setText("");
jtx.setText(jtx.getText()+"2");
z=0;
}
}
if(s.equals("3"))
{
if(z==0)
{
jtx.setText(jtx.getText()+"3");
}
else
{
jtx.setText("");
jtx.setText(jtx.getText()+"3");
z=0;
}
}
if(s.equals("4"))
{
if(z==0)
{
jtx.setText(jtx.getText()+"4");
}
else
{
jtx.setText("");
jtx.setText(jtx.getText()+"4");
z=0;
}
}
if(s.equals("5"))
{
if(z==0)
{
jtx.setText(jtx.getText()+"5");
}
else
{
jtx.setText("");
jtx.setText(jtx.getText()+"5");
z=0;
}
}
if(s.equals("6"))
{
if(z==0)
{
jtx.setText(jtx.getText()+"6");
}
else
{
jtx.setText("");
jtx.setText(jtx.getText()+"6");
z=0;
}
}
if(s.equals("7"))
{
if(z==0)
{
jtx.setText(jtx.getText()+"7");
}
else
{
jtx.setText("");
jtx.setText(jtx.getText()+"7");
z=0;
}
}
if(s.equals("8"))
{
if(z==0)
{
jtx.setText(jtx.getText()+"8");
}
else
{
jtx.setText("");
jtx.setText(jtx.getText()+"8");
z=0;
}
}
if(s.equals("9"))
{
if(z==0)
{
jtx.setText(jtx.getText()+"9");
}
else
{
jtx.setText("");
jtx.setText(jtx.getText()+"9");
z=0;
}
}
if(s.equals("0"))
{
if(z==0)
{
jtx.setText(jtx.getText()+"0");
}
else
{
jtx.setText("");
jtx.setText(jtx.getText()+"0");
z=0;
}
}
if(s.equals("AC"))
{
jtx.setText("");
x=0;
y=0;
z=0;
}
if(s.equals("log"))
{
if(jtx.getText().equals(""))
{
jtx.setText("");
}
else
{
a=Math.log(Double.parseDouble(jtx.getText()));
jtx.setText("");
jtx.setText(jtx.getText() + a);
}
}
if(s.equals("1/x"))
{
if(jtx.getText().equals(""))
{
jtx.setText("");
}
else
{
a=1/Double.parseDouble(jtx.getText());
jtx.setText("");
jtx.setText(jtx.getText() + a);
}
}
if(s.equals("Exp"))
{
if(jtx.getText().equals(""))
{
jtx.setText("");
}
else
{
a=Math.exp(Double.parseDouble(jtx.getText()));
jtx.setText("");
jtx.setText(jtx.getText() + a);
}
}
if(s.equals("x^2"))
{
if(jtx.getText().equals(""))
{
jtx.setText("");
}
else
{
a=Math.pow(Double.parseDouble(jtx.getText()),2);
jtx.setText("");
jtx.setText(jtx.getText() + a);
}
}
if(s.equals("x^3"))
{
if(jtx.getText().equals(""))
{
jtx.setText("");
}
else
{
a=Math.pow(Double.parseDouble(jtx.getText()),3);
jtx.setText("");
jtx.setText(jtx.getText() + a);
}
}
if(s.equals("+/-"))
{
if(x==0)
{
jtx.setText("-"+jtx.getText());
x=1;
}
else
{
jtx.setText(jtx.getText());
}
}
if(s.equals("."))
{
if(y==0)
{
jtx.setText(jtx.getText()+".");
y=1;
}
else
{
jtx.setText(jtx.getText());
}
}
if(s.equals("+"))
{
if(jtx.getText().equals(""))
{
jtx.setText("");
temp=0;
ch='+';
}
else
{
temp=Double.parseDouble(jtx.getText());
jtx.setText("");
ch='+';
y=0;
x=0;
}
jtx.requestFocus();
}
if(s.equals("-"))
{
if(jtx.getText().equals(""))
{
jtx.setText("");
temp=0;
ch='-';
}
else
{
x=0;
y=0;
temp=Double.parseDouble(jtx.getText());
jtx.setText("");
ch='-';
}
jtx.requestFocus();
}
if(s.equals("/"))
{
if(jtx.getText().equals(""))
{
jtx.setText("");
temp=1;
ch='/';
}
else
{
x=0;
y=0;
temp=Double.parseDouble(jtx.getText());
ch='/';
jtx.setText("");
}
jtx.requestFocus();
}
if(s.equals("*"))
{
if(jtx.getText().equals(""))
{
jtx.setText("");
temp=1;
ch='*';
}
else
{
x=0;
y=0;
temp=Double.parseDouble(jtx.getText());
ch='*';
jtx.setText("");
}
jtx.requestFocus();
}
if(s.equals("MC"))
{
m1=0;
jtx.setText("");
}
if(s.equals("MR"))
{
jtx.setText("");
jtx.setText(jtx.getText() + m1);
}
if(s.equals("M+"))
{
if(k==1)
{
m1=Double.parseDouble(jtx.getText());
k++;
}
else
{
m1+=Double.parseDouble(jtx.getText());
jtx.setText(""+m1);
}
}
if(s.equals("M-"))
{
if(k==1)
{
m1=Double.parseDouble(jtx.getText());
k++;
}
else
{
m1-=Double.parseDouble(jtx.getText());
jtx.setText(""+m1);
}
}
if(s.equals("Sqrt"))
{
if(jtx.getText().equals(""))
{
jtx.setText("");
}
else
{
a=Math.sqrt(Double.parseDouble(jtx.getText()));
jtx.setText("");
jtx.setText(jtx.getText() + a);
}
}
if(s.equals("SIN"))
{
if(jtx.getText().equals(""))
{
jtx.setText("");
}
else
{
a=Math.sin(Double.parseDouble(jtx.getText()));
jtx.setText("");
jtx.setText(jtx.getText() + a);
}
}
if(s.equals("COS"))
{
if(jtx.getText().equals(""))
{
jtx.setText("");
}
else
{
a=Math.cos(Double.parseDouble(jtx.getText()));
jtx.setText("");
jtx.setText(jtx.getText() + a);
}
}
if(s.equals("TAN"))
{
if(jtx.getText().equals(""))
{
jtx.setText("");
}
else
{
a=Math.tan(Double.parseDouble(jtx.getText()));
jtx.setText("");
jtx.setText(jtx.getText() + a);
}
}
if(s.equals("="))
{
if(jtx.getText().equals(""))
{
jtx.setText("");
}
else
{
temp1 = Double.parseDouble(jtx.getText());
switch(ch)
{
case '+':
result=temp+temp1;
break;
case '-':
result=temp-temp1;
break;
case '/':
result=temp/temp1;
break;
case '*':
result=temp*temp1;
break;
}
jtx.setText("");
jtx.setText(jtx.getText() + result);
z=1;
}
}
jtx.requestFocus();
}
public static void main(String args[])
{
calculator n=new calculator();
n.setTitle("CALCULATOR");
n.setSize(370,250);
n.setResizable(false);
n.setVisible(true);
}
}
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class calculator extends JFrame implements ActionListener
{
JTextField jtx;
double temp,temp1,result,a;
static double m1,m2;
int k=1,x=0,y=0,z=0;
char ch;
JButton
one,two,three,four,five,six,seven,eight,nine,zero,clr,pow2,pow3,exp;
JButton
plus,min,div,lg,rec,mul,eq,plmi,poin,mr,mc,mp,mm,sqrt,sin,cos,tan;
JMenuBar bar;
JMenu view;
JMenuItem exit;
JRadioButtonMenuItem standard,scientific;
JSeparator jp;
ButtonGroup bg;
Container cont;
JPanel textPanel,syntpanel,buttonpanel;
calculator()
{
cont=getContentPane();
cont.setLayout(new BorderLayout());
JPanel textpanel=new JPanel();
Font font=new Font("Arial",Font.PLAIN,18);
jtx=new JTextField(25);
jtx.setFont(font);
jtx.setHorizontalAlignment(SwingConstants.RIGHT);
jtx.addKeyListener(new KeyAdapter()
{
public void keyTyped(KeyEvent keyevent)
{
char c=keyevent.getKeyChar();
if(c>='0' && c<='9')
{
}
else
{
keyevent.consume();
}
}
});
textpanel.add(jtx);
buttonpanel=new JPanel();
buttonpanel.setLayout(new GridLayout(5,4,2,2));
boolean t=true;
syntpanel=new JPanel();
syntpanel.setLayout(new GridLayout(5,1));
bar=new JMenuBar();
view=new JMenu("View");
standard =new JRadioButtonMenuItem("Standard",true);
standard.setMnemonic('S');
standard.addItemListener(new radiohandler());
scientific =new JRadioButtonMenuItem("Sceintific");
standard.setMnemonic('c');
scientific.addItemListener(new radiohandler());
jp=new JSeparator();
exit=new JMenuItem("Exit");
standard.setMnemonic('E');
exit.addActionListener(this);
bg=new ButtonGroup();
bg.add(standard);
bg.add(scientific);
view.add(standard);
view.add(scientific);
view.add(jp);
view.add(exit);
bar.add(view);
setJMenuBar(bar);
mr=new JButton("MR");
buttonpanel.add(mr);
mr.addActionListener(this);
seven=new JButton("7");
buttonpanel.add(seven);
seven.addActionListener(this);
eight=new JButton("8");
buttonpanel.add(eight);
eight.addActionListener(this);
nine=new JButton("9");
buttonpanel.add(nine);
nine.addActionListener(this);
clr=new JButton("AC");
buttonpanel.add(clr);
clr.addActionListener(this);
mc=new JButton("MC");
buttonpanel.add(mc);
mc.addActionListener(this);
four=new JButton("4");
buttonpanel.add(four);
four.addActionListener(this);
five=new JButton("5");
buttonpanel.add(five);
five.addActionListener(this);
six=new JButton("6");
buttonpanel.add(six);
six.addActionListener(this);
mul=new JButton("*");
buttonpanel.add(mul);
mul.addActionListener(this);
mp=new JButton("M+");
buttonpanel.add(mp);
mp.addActionListener(this);
one=new JButton("1");
buttonpanel.add(one);
one.addActionListener(this);
two=new JButton("2");
buttonpanel.add(two);
two.addActionListener(this);
three=new JButton("3");
buttonpanel.add(three);
three.addActionListener(this);
min=new JButton("-");
buttonpanel.add(min);
min.addActionListener(this);
mm=new JButton("M-");
buttonpanel.add(mm);
mm.addActionListener(this);
zero=new JButton("0");
buttonpanel.add(zero);
zero.addActionListener(this);
plmi=new JButton("+/-");
buttonpanel.add(plmi);
plmi.addActionListener(this);
poin=new JButton(".");
buttonpanel.add(poin);
poin.addActionListener(this);
plus=new JButton("+");
buttonpanel.add(plus);
plus.addActionListener(this);
rec=new JButton("1/x");
buttonpanel.add(rec);
rec.addActionListener(this);
sqrt=new JButton("Sqrt");
buttonpanel.add(sqrt);
sqrt.addActionListener(this);
lg=new JButton("log");
buttonpanel.add(lg);
lg.addActionListener(this);
div=new JButton("/");
div.addActionListener(this);
buttonpanel.add(div);
eq=new JButton("=");
buttonpanel.add(eq);
eq.addActionListener(this);
sin=new JButton("SIN");
syntpanel.add(sin);
sin.addActionListener(this);
cos=new JButton("COS");
syntpanel.add(cos);
cos.addActionListener(this);
tan=new JButton("TAN");
syntpanel.add(tan);
tan.addActionListener(this);
pow2=new JButton("x^2");
syntpanel.add(pow2);
pow2.addActionListener(this);
pow3=new JButton("x^3");
syntpanel.add(pow3);
pow3.addActionListener(this);
exp=new JButton("Exp");
exp.addActionListener(this);
cont.add("Center",buttonpanel);
cont.add("North",textpanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class radiohandler implements ItemListener
{
public void itemStateChanged(ItemEvent ie)
{
AbstractButton button=(AbstractButton)ie.getItem();
String label=button.getText();
{
if(label.equals("Standard"))
{
cont.remove(syntpanel);
validate();
}
if(label.equals("Sceintific"))
{
cont.add("West",syntpanel);
validate();
}
}
}
}
public void actionPerformed(ActionEvent e)
{
String s=e.getActionCommand();
if(s.equals("Exit"))
{
System.exit(0);
}
if(s.equals("1"))
{
if(z==0)
{
jtx.setText(jtx.getText()+"1");
}
else
{
jtx.setText("");
jtx.setText(jtx.getText()+"1");
z=0;
}
}
if(s.equals("2"))
{
if(z==0)
{
jtx.setText(jtx.getText()+"2");
}
else
{
jtx.setText("");
jtx.setText(jtx.getText()+"2");
z=0;
}
}
if(s.equals("3"))
{
if(z==0)
{
jtx.setText(jtx.getText()+"3");
}
else
{
jtx.setText("");
jtx.setText(jtx.getText()+"3");
z=0;
}
}
if(s.equals("4"))
{
if(z==0)
{
jtx.setText(jtx.getText()+"4");
}
else
{
jtx.setText("");
jtx.setText(jtx.getText()+"4");
z=0;
}
}
if(s.equals("5"))
{
if(z==0)
{
jtx.setText(jtx.getText()+"5");
}
else
{
jtx.setText("");
jtx.setText(jtx.getText()+"5");
z=0;
}
}
if(s.equals("6"))
{
if(z==0)
{
jtx.setText(jtx.getText()+"6");
}
else
{
jtx.setText("");
jtx.setText(jtx.getText()+"6");
z=0;
}
}
if(s.equals("7"))
{
if(z==0)
{
jtx.setText(jtx.getText()+"7");
}
else
{
jtx.setText("");
jtx.setText(jtx.getText()+"7");
z=0;
}
}
if(s.equals("8"))
{
if(z==0)
{
jtx.setText(jtx.getText()+"8");
}
else
{
jtx.setText("");
jtx.setText(jtx.getText()+"8");
z=0;
}
}
if(s.equals("9"))
{
if(z==0)
{
jtx.setText(jtx.getText()+"9");
}
else
{
jtx.setText("");
jtx.setText(jtx.getText()+"9");
z=0;
}
}
if(s.equals("0"))
{
if(z==0)
{
jtx.setText(jtx.getText()+"0");
}
else
{
jtx.setText("");
jtx.setText(jtx.getText()+"0");
z=0;
}
}
if(s.equals("AC"))
{
jtx.setText("");
x=0;
y=0;
z=0;
}
if(s.equals("log"))
{
if(jtx.getText().equals(""))
{
jtx.setText("");
}
else
{
a=Math.log(Double.parseDouble(jtx.getText()));
jtx.setText("");
jtx.setText(jtx.getText() + a);
}
}
if(s.equals("1/x"))
{
if(jtx.getText().equals(""))
{
jtx.setText("");
}
else
{
a=1/Double.parseDouble(jtx.getText());
jtx.setText("");
jtx.setText(jtx.getText() + a);
}
}
if(s.equals("Exp"))
{
if(jtx.getText().equals(""))
{
jtx.setText("");
}
else
{
a=Math.exp(Double.parseDouble(jtx.getText()));
jtx.setText("");
jtx.setText(jtx.getText() + a);
}
}
if(s.equals("x^2"))
{
if(jtx.getText().equals(""))
{
jtx.setText("");
}
else
{
a=Math.pow(Double.parseDouble(jtx.getText()),2);
jtx.setText("");
jtx.setText(jtx.getText() + a);
}
}
if(s.equals("x^3"))
{
if(jtx.getText().equals(""))
{
jtx.setText("");
}
else
{
a=Math.pow(Double.parseDouble(jtx.getText()),3);
jtx.setText("");
jtx.setText(jtx.getText() + a);
}
}
if(s.equals("+/-"))
{
if(x==0)
{
jtx.setText("-"+jtx.getText());
x=1;
}
else
{
jtx.setText(jtx.getText());
}
}
if(s.equals("."))
{
if(y==0)
{
jtx.setText(jtx.getText()+".");
y=1;
}
else
{
jtx.setText(jtx.getText());
}
}
if(s.equals("+"))
{
if(jtx.getText().equals(""))
{
jtx.setText("");
temp=0;
ch='+';
}
else
{
temp=Double.parseDouble(jtx.getText());
jtx.setText("");
ch='+';
y=0;
x=0;
}
jtx.requestFocus();
}
if(s.equals("-"))
{
if(jtx.getText().equals(""))
{
jtx.setText("");
temp=0;
ch='-';
}
else
{
x=0;
y=0;
temp=Double.parseDouble(jtx.getText());
jtx.setText("");
ch='-';
}
jtx.requestFocus();
}
if(s.equals("/"))
{
if(jtx.getText().equals(""))
{
jtx.setText("");
temp=1;
ch='/';
}
else
{
x=0;
y=0;
temp=Double.parseDouble(jtx.getText());
ch='/';
jtx.setText("");
}
jtx.requestFocus();
}
if(s.equals("*"))
{
if(jtx.getText().equals(""))
{
jtx.setText("");
temp=1;
ch='*';
}
else
{
x=0;
y=0;
temp=Double.parseDouble(jtx.getText());
ch='*';
jtx.setText("");
}
jtx.requestFocus();
}
if(s.equals("MC"))
{
m1=0;
jtx.setText("");
}
if(s.equals("MR"))
{
jtx.setText("");
jtx.setText(jtx.getText() + m1);
}
if(s.equals("M+"))
{
if(k==1)
{
m1=Double.parseDouble(jtx.getText());
k++;
}
else
{
m1+=Double.parseDouble(jtx.getText());
jtx.setText(""+m1);
}
}
if(s.equals("M-"))
{
if(k==1)
{
m1=Double.parseDouble(jtx.getText());
k++;
}
else
{
m1-=Double.parseDouble(jtx.getText());
jtx.setText(""+m1);
}
}
if(s.equals("Sqrt"))
{
if(jtx.getText().equals(""))
{
jtx.setText("");
}
else
{
a=Math.sqrt(Double.parseDouble(jtx.getText()));
jtx.setText("");
jtx.setText(jtx.getText() + a);
}
}
if(s.equals("SIN"))
{
if(jtx.getText().equals(""))
{
jtx.setText("");
}
else
{
a=Math.sin(Double.parseDouble(jtx.getText()));
jtx.setText("");
jtx.setText(jtx.getText() + a);
}
}
if(s.equals("COS"))
{
if(jtx.getText().equals(""))
{
jtx.setText("");
}
else
{
a=Math.cos(Double.parseDouble(jtx.getText()));
jtx.setText("");
jtx.setText(jtx.getText() + a);
}
}
if(s.equals("TAN"))
{
if(jtx.getText().equals(""))
{
jtx.setText("");
}
else
{
a=Math.tan(Double.parseDouble(jtx.getText()));
jtx.setText("");
jtx.setText(jtx.getText() + a);
}
}
if(s.equals("="))
{
if(jtx.getText().equals(""))
{
jtx.setText("");
}
else
{
temp1 = Double.parseDouble(jtx.getText());
switch(ch)
{
case '+':
result=temp+temp1;
break;
case '-':
result=temp-temp1;
break;
case '/':
result=temp/temp1;
break;
case '*':
result=temp*temp1;
break;
}
jtx.setText("");
jtx.setText(jtx.getText() + result);
z=1;
}
}
jtx.requestFocus();
}
public static void main(String args[])
{
calculator n=new calculator();
n.setTitle("CALCULATOR");
n.setSize(370,250);
n.setResizable(false);
n.setVisible(true);
}
}
School Management System Project In Java
//Case Study
import java.awt.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
public class ProjectX extends JFrame implements ChangeListener,
ActionListener
{
static int choice = 0;
static String line = "--------------------------------";
DataInputStream inputData = new DataInputStream(System.in);
private Registration studentDetails = new Registration();
int topScore = studentDetails.getTopScore();
int passMarks = studentDetails.getPassMarks();
int firstClass = studentDetails.getFirstClass();
int secondClass = studentDetails.getSecondClass();
JTabbedPane tabbedPane = new JTabbedPane();
JLabel statusLabel = new JLabel();
JLabel titleLabel = new JLabel("Student Software Beta Edition");
JPanel addStudentPanel = new JPanel();
JTextField studentName = new JTextField();
JTextField physicsMarks = new JTextField();
JTextField biologyMarks = new JTextField();
JTextField mathsMarks = new JTextField();
JButton submitDetails = new JButton("Submit Details");
JPanel studentDetailsPanel = new JPanel();
JTextField studentID1 = new JTextField();
JTextArea studentInfo = new JTextArea();
JButton submitID1 = new JButton("Submit ID");
JPanel studentGradePanel = new JPanel();
JTextField studentID2 = new JTextField();
JTextArea studentGrade = new JTextArea();
JButton submitID2 = new JButton("Submit ID");
JPanel numberPassedPanel = new JPanel();
JTextArea studentPassed = new JTextArea();
JPanel classTopperPanel = new JPanel();
JTextArea studentTopper = new JTextArea();
public ProjectX(String frameTitle)
{
super(frameTitle);
setResizable(true);
setSize(400,400);
submitDetails.addActionListener(this);
submitID1.addActionListener(this);
submitID2.addActionListener(this);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(titleLabel,"North");
tabbedPane.addTab("Add Student",addStudentPanel);
addStudentPanel.setLayout(new GridLayout(8,2,5,5));
addStudentPanel.add(new JLabel("Student Name: "));
addStudentPanel.add(studentName);
addStudentPanel.add(new JLabel("Physics Marks: "));
addStudentPanel.add(physicsMarks);
addStudentPanel.add(new JLabel("Biology Marks: "));
addStudentPanel.add(biologyMarks);
addStudentPanel.add(new JLabel("Maths Marks: "));
addStudentPanel.add(mathsMarks);
addStudentPanel.add(submitDetails);
tabbedPane.addTab("Student Details",studentDetailsPanel);
studentDetailsPanel.add(new JLabel("Enter Student ID: "));
studentDetailsPanel.add(studentID1);
studentDetailsPanel.add(submitID1);
studentDetailsPanel.add(new JLabel("Student Details:"));
studentDetailsPanel.add(studentInfo);
tabbedPane.addTab("Student Grade",studentGradePanel);
studentGradePanel.setLayout(new GridLayout(5,2,5,5));
studentGradePanel.add(new JLabel("Enter Student ID: "));
studentGradePanel.add(studentID2);
studentGradePanel.add(submitID2);
studentGradePanel.add(new JLabel("Student Grade:"));
studentGradePanel.add(studentGrade);
tabbedPane.addTab("Passed Student",numberPassedPanel);
numberPassedPanel.setLayout(new GridLayout(2,2,5,5));
numberPassedPanel.add(new JLabel("Number of Student Passed: "));
numberPassedPanel.add(studentPassed);
tabbedPane.addTab("Class Topper",classTopperPanel);
classTopperPanel.setLayout(new GridLayout(2,2,5,5));
classTopperPanel.add(new JLabel("Here are the class Toppers: "));
classTopperPanel.add(studentTopper);
tabbedPane.addChangeListener(this);
getContentPane().add(tabbedPane,"Center");
statusLabel.setText("Status: Normal");
getContentPane().add(statusLabel,"South");
setVisible(true);
}
public static void main(String args[])
{
ProjectX outputScreen = new ProjectX("Case Study");
}
public String setStudentInfo()
{
int id = studentDetails.addStudent(studentName.getText(),
Integer.parseInt(physicsMarks.getText()),
Integer.parseInt(biologyMarks.getText()),
Integer.parseInt(mathsMarks.getText()));
return
(" " +
line +
"Record Created For " + studentName +
"
" +
"Student ID: " + id +
"
" +
line );
}
public String getStudentInfo()
{
int id = Integer.parseInt(studentID1.getText());
if(studentDetails.getStudentDetails(id))
return ("
" +
line +
"Student Details
" +
line +
"Student ID:" + " " + id + "
" +
"Student Name:" + " " + studentDetails.studentName + "
" +
"Physics Marks:" + " " + studentDetails.physicsMarks + "
" +
"Biology Marks:" + " " + studentDetails.biologyMarks + "
" +
"Maths Marks:" + " " + studentDetails.mathsMarks + "
" +
line );
else
return("
Records Not Found for ID " + id);
}
public String getStudentGrade()
{
int id = Integer.parseInt(studentID2.getText());
studentDetails.getStudentDetails(id);
String grade;
if(studentDetails.studentName == null)
{
System.out.println("
Records Not Found for ID " + id);
return null;
}
if(studentDetails.physicsMarks <>
studentDetails.biologyMarks <>
passMarks)
{
grade = "Failed";
}
else
{
int avgMarks = (studentDetails.physicsMarks +
studentDetails.biologyMarks + studentDetails.mathsMarks)/3;
if(avgMarks >= passMarks && avgMarks < grade =" ">
Class";
else if(avgMarks >= secondClass && avgMarks < grade ="
"Second Class";
else if(avgMarks >= firstClass && avgMarks < grade =" ">
Class";
else grade = "Distinction";
}
return(line + "Grade For " + studentDetails.studentName + " is " + grade
+ "
" + line);
}
public String getNumberPasses()
{
int lastID = Registration.getNextID() -1;
boolean passed = true;
int numberPassed = 0;
for(int id = 1; id <= lastID; id++)
{
studentDetails.getStudentDetails(id);
if(studentDetails.physicsMarks >= passMarks &&
studentDetails.biologyMarks >= passMarks && studentDetails.mathsMarks >=
passMarks) numberPassed++;
}
return(line + "Number of Student Passed: " + numberPassed + "
" +
line);
}
public String getClassTopper()
{
int lastID = Registration.getNextID() -1;
String classTopper;
StringBuffer buffer = new StringBuffer(500);
int topMarks = 0;
for(int id = 1; id <= lastID; id++)
{
studentDetails.getStudentDetails(id);
int studentMarks = studentDetails.physicsMarks +
studentDetails.biologyMarks + studentDetails.mathsMarks;
if(studentMarks > topMarks) topMarks = studentMarks;
}
buffer.append(line + "Student Having Top Marks:
");
for(int id = 1; id <= lastID; id++)
{
studentDetails.getStudentDetails(id);
int studentMarks = studentDetails.physicsMarks +
studentDetails.biologyMarks + studentDetails.mathsMarks;
if(studentMarks == topMarks)
{
buffer.append(studentDetails.studentName + " Having Total Marks: " +
topMarks + "
");
}
}
buffer.append(line);
return(buffer.toString());
}
public void stateChanged(ChangeEvent e)
{
switch(tabbedPane.getSelectedIndex())
{
case 3: studentPassed.setText(getNumberPasses());
break;
case 4: studentTopper.setText(getClassTopper());
break;
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == submitID1)
{
studentInfo.setText(getStudentInfo());
}
else if(e.getSource() == submitID2)
{
studentGrade.setText(getStudentGrade());
}
if(e.getSource() == submitDetails)
{
setStudentInfo();
}
}
}
//Registration Class
class Registration
{
private int topScore = 90;
private int passMarks = 35;
private int firstClass = 65;
private int secondClass = 45;
private static String idFile = "id.dat";
private static String studentFile = "stdfile.dat";
public int id;
public String studentName;
public int physicsMarks;
public int biologyMarks;
public int mathsMarks;
public int addStudent(String studentName, int physicsMarks, int
biologyMarks, int mathsMarks)
{
int id = 0;
try
{
FileWriter fileOutput = new FileWriter(Registration.studentFile,true);
id = Registration.getNextID();
String buffer = id + "|" + studentName + "|" + physicsMarks + "|" +
biologyMarks + "|" + mathsMarks + "
";
fileOutput.write(buffer);
fileOutput.close();
Registration.setID(id);
}
catch(IOException e)
{
System.err.println(e.toString());
System.exit(1);
}
return id;
}
//Function to get the details of a student given the ID
public boolean getStudentDetails(int id)
{
try
{
FileReader fileInput = new FileReader(Registration.studentFile);
BufferedReader br = new BufferedReader(fileInput);
{
String str;
while((str = br.readLine()) != null)
{
StringTokenizer fields = new StringTokenizer(str,"|");
if(Integer.parseInt(fields.nextToken()) == id)
{
this.id = id;
this.studentName = fields.nextToken();
this.physicsMarks = Integer.parseInt(fields.nextToken());
this.biologyMarks = Integer.parseInt(fields.nextToken());
this.mathsMarks = Integer.parseInt(fields.nextToken());
return true;
}
}
}
}
catch(IOException e)
{
System.err.println(e.toString());
System.exit(1);
}
return false;
}
public int getTopScore()
{
return topScore;
}
public int getPassMarks()
{
return passMarks;
}
public int getFirstClass()
{
return firstClass;
}
public int getSecondClass()
{
return secondClass;
}
//Function to get the next ID available
public static int getNextID()
{
int id = 0;
try
{
RandomAccessFile studentIDFile = new
RandomAccessFile(Registration.idFile,"rw");
if(studentIDFile.length() == 0)
{
id = 0;
}
else id = studentIDFile.readInt();
id++;
studentIDFile.close();
}
catch(IOException e)
{
System.err.println(e.toString());
System.exit(1);
}
return id;
}
//Function to Store current ID in a file
public static void setID(int id)
{
try
{
RandomAccessFile studentIDFile = new
RandomAccessFile(Registration.idFile,"rw");
studentIDFile.seek(0);
studentIDFile.writeInt(id);
studentIDFile.close();
}
catch(IOException e)
{
System.err.println(e.toString());
System.exit(1);
}
}
}
import java.awt.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
public class ProjectX extends JFrame implements ChangeListener,
ActionListener
{
static int choice = 0;
static String line = "--------------------------------";
DataInputStream inputData = new DataInputStream(System.in);
private Registration studentDetails = new Registration();
int topScore = studentDetails.getTopScore();
int passMarks = studentDetails.getPassMarks();
int firstClass = studentDetails.getFirstClass();
int secondClass = studentDetails.getSecondClass();
JTabbedPane tabbedPane = new JTabbedPane();
JLabel statusLabel = new JLabel();
JLabel titleLabel = new JLabel("Student Software Beta Edition");
JPanel addStudentPanel = new JPanel();
JTextField studentName = new JTextField();
JTextField physicsMarks = new JTextField();
JTextField biologyMarks = new JTextField();
JTextField mathsMarks = new JTextField();
JButton submitDetails = new JButton("Submit Details");
JPanel studentDetailsPanel = new JPanel();
JTextField studentID1 = new JTextField();
JTextArea studentInfo = new JTextArea();
JButton submitID1 = new JButton("Submit ID");
JPanel studentGradePanel = new JPanel();
JTextField studentID2 = new JTextField();
JTextArea studentGrade = new JTextArea();
JButton submitID2 = new JButton("Submit ID");
JPanel numberPassedPanel = new JPanel();
JTextArea studentPassed = new JTextArea();
JPanel classTopperPanel = new JPanel();
JTextArea studentTopper = new JTextArea();
public ProjectX(String frameTitle)
{
super(frameTitle);
setResizable(true);
setSize(400,400);
submitDetails.addActionListener(this);
submitID1.addActionListener(this);
submitID2.addActionListener(this);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(titleLabel,"North");
tabbedPane.addTab("Add Student",addStudentPanel);
addStudentPanel.setLayout(new GridLayout(8,2,5,5));
addStudentPanel.add(new JLabel("Student Name: "));
addStudentPanel.add(studentName);
addStudentPanel.add(new JLabel("Physics Marks: "));
addStudentPanel.add(physicsMarks);
addStudentPanel.add(new JLabel("Biology Marks: "));
addStudentPanel.add(biologyMarks);
addStudentPanel.add(new JLabel("Maths Marks: "));
addStudentPanel.add(mathsMarks);
addStudentPanel.add(submitDetails);
tabbedPane.addTab("Student Details",studentDetailsPanel);
studentDetailsPanel.add(new JLabel("Enter Student ID: "));
studentDetailsPanel.add(studentID1);
studentDetailsPanel.add(submitID1);
studentDetailsPanel.add(new JLabel("Student Details:"));
studentDetailsPanel.add(studentInfo);
tabbedPane.addTab("Student Grade",studentGradePanel);
studentGradePanel.setLayout(new GridLayout(5,2,5,5));
studentGradePanel.add(new JLabel("Enter Student ID: "));
studentGradePanel.add(studentID2);
studentGradePanel.add(submitID2);
studentGradePanel.add(new JLabel("Student Grade:"));
studentGradePanel.add(studentGrade);
tabbedPane.addTab("Passed Student",numberPassedPanel);
numberPassedPanel.setLayout(new GridLayout(2,2,5,5));
numberPassedPanel.add(new JLabel("Number of Student Passed: "));
numberPassedPanel.add(studentPassed);
tabbedPane.addTab("Class Topper",classTopperPanel);
classTopperPanel.setLayout(new GridLayout(2,2,5,5));
classTopperPanel.add(new JLabel("Here are the class Toppers: "));
classTopperPanel.add(studentTopper);
tabbedPane.addChangeListener(this);
getContentPane().add(tabbedPane,"Center");
statusLabel.setText("Status: Normal");
getContentPane().add(statusLabel,"South");
setVisible(true);
}
public static void main(String args[])
{
ProjectX outputScreen = new ProjectX("Case Study");
}
public String setStudentInfo()
{
int id = studentDetails.addStudent(studentName.getText(),
Integer.parseInt(physicsMarks.getText()),
Integer.parseInt(biologyMarks.getText()),
Integer.parseInt(mathsMarks.getText()));
return
(" " +
line +
"Record Created For " + studentName +
"
" +
"Student ID: " + id +
"
" +
line );
}
public String getStudentInfo()
{
int id = Integer.parseInt(studentID1.getText());
if(studentDetails.getStudentDetails(id))
return ("
" +
line +
"Student Details
" +
line +
"Student ID:" + " " + id + "
" +
"Student Name:" + " " + studentDetails.studentName + "
" +
"Physics Marks:" + " " + studentDetails.physicsMarks + "
" +
"Biology Marks:" + " " + studentDetails.biologyMarks + "
" +
"Maths Marks:" + " " + studentDetails.mathsMarks + "
" +
line );
else
return("
Records Not Found for ID " + id);
}
public String getStudentGrade()
{
int id = Integer.parseInt(studentID2.getText());
studentDetails.getStudentDetails(id);
String grade;
if(studentDetails.studentName == null)
{
System.out.println("
Records Not Found for ID " + id);
return null;
}
if(studentDetails.physicsMarks <>
studentDetails.biologyMarks <>
passMarks)
{
grade = "Failed";
}
else
{
int avgMarks = (studentDetails.physicsMarks +
studentDetails.biologyMarks + studentDetails.mathsMarks)/3;
if(avgMarks >= passMarks && avgMarks < grade =" ">
Class";
else if(avgMarks >= secondClass && avgMarks < grade ="
"Second Class";
else if(avgMarks >= firstClass && avgMarks < grade =" ">
Class";
else grade = "Distinction";
}
return(line + "Grade For " + studentDetails.studentName + " is " + grade
+ "
" + line);
}
public String getNumberPasses()
{
int lastID = Registration.getNextID() -1;
boolean passed = true;
int numberPassed = 0;
for(int id = 1; id <= lastID; id++)
{
studentDetails.getStudentDetails(id);
if(studentDetails.physicsMarks >= passMarks &&
studentDetails.biologyMarks >= passMarks && studentDetails.mathsMarks >=
passMarks) numberPassed++;
}
return(line + "Number of Student Passed: " + numberPassed + "
" +
line);
}
public String getClassTopper()
{
int lastID = Registration.getNextID() -1;
String classTopper;
StringBuffer buffer = new StringBuffer(500);
int topMarks = 0;
for(int id = 1; id <= lastID; id++)
{
studentDetails.getStudentDetails(id);
int studentMarks = studentDetails.physicsMarks +
studentDetails.biologyMarks + studentDetails.mathsMarks;
if(studentMarks > topMarks) topMarks = studentMarks;
}
buffer.append(line + "Student Having Top Marks:
");
for(int id = 1; id <= lastID; id++)
{
studentDetails.getStudentDetails(id);
int studentMarks = studentDetails.physicsMarks +
studentDetails.biologyMarks + studentDetails.mathsMarks;
if(studentMarks == topMarks)
{
buffer.append(studentDetails.studentName + " Having Total Marks: " +
topMarks + "
");
}
}
buffer.append(line);
return(buffer.toString());
}
public void stateChanged(ChangeEvent e)
{
switch(tabbedPane.getSelectedIndex())
{
case 3: studentPassed.setText(getNumberPasses());
break;
case 4: studentTopper.setText(getClassTopper());
break;
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == submitID1)
{
studentInfo.setText(getStudentInfo());
}
else if(e.getSource() == submitID2)
{
studentGrade.setText(getStudentGrade());
}
if(e.getSource() == submitDetails)
{
setStudentInfo();
}
}
}
//Registration Class
class Registration
{
private int topScore = 90;
private int passMarks = 35;
private int firstClass = 65;
private int secondClass = 45;
private static String idFile = "id.dat";
private static String studentFile = "stdfile.dat";
public int id;
public String studentName;
public int physicsMarks;
public int biologyMarks;
public int mathsMarks;
public int addStudent(String studentName, int physicsMarks, int
biologyMarks, int mathsMarks)
{
int id = 0;
try
{
FileWriter fileOutput = new FileWriter(Registration.studentFile,true);
id = Registration.getNextID();
String buffer = id + "|" + studentName + "|" + physicsMarks + "|" +
biologyMarks + "|" + mathsMarks + "
";
fileOutput.write(buffer);
fileOutput.close();
Registration.setID(id);
}
catch(IOException e)
{
System.err.println(e.toString());
System.exit(1);
}
return id;
}
//Function to get the details of a student given the ID
public boolean getStudentDetails(int id)
{
try
{
FileReader fileInput = new FileReader(Registration.studentFile);
BufferedReader br = new BufferedReader(fileInput);
{
String str;
while((str = br.readLine()) != null)
{
StringTokenizer fields = new StringTokenizer(str,"|");
if(Integer.parseInt(fields.nextToken()) == id)
{
this.id = id;
this.studentName = fields.nextToken();
this.physicsMarks = Integer.parseInt(fields.nextToken());
this.biologyMarks = Integer.parseInt(fields.nextToken());
this.mathsMarks = Integer.parseInt(fields.nextToken());
return true;
}
}
}
}
catch(IOException e)
{
System.err.println(e.toString());
System.exit(1);
}
return false;
}
public int getTopScore()
{
return topScore;
}
public int getPassMarks()
{
return passMarks;
}
public int getFirstClass()
{
return firstClass;
}
public int getSecondClass()
{
return secondClass;
}
//Function to get the next ID available
public static int getNextID()
{
int id = 0;
try
{
RandomAccessFile studentIDFile = new
RandomAccessFile(Registration.idFile,"rw");
if(studentIDFile.length() == 0)
{
id = 0;
}
else id = studentIDFile.readInt();
id++;
studentIDFile.close();
}
catch(IOException e)
{
System.err.println(e.toString());
System.exit(1);
}
return id;
}
//Function to Store current ID in a file
public static void setID(int id)
{
try
{
RandomAccessFile studentIDFile = new
RandomAccessFile(Registration.idFile,"rw");
studentIDFile.seek(0);
studentIDFile.writeInt(id);
studentIDFile.close();
}
catch(IOException e)
{
System.err.println(e.toString());
System.exit(1);
}
}
}
Subscribe to:
Posts (Atom)