0% found this document useful (0 votes)
48 views

Oops Lab

1. A Java application was developed to implement currency, distance, and time converters using packages. Packages were created called "converter", "distance", and "time" with class files Dollar.java, Distance.java, and Time.java respectively. 2. The packages were compiled and a main class "Converter" was written in a separate directory to access and use the packages. 3. Based on the user's choice, the appropriate conversion method like currency conversion, distance conversion or time conversion was called.

Uploaded by

Rogith M
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

Oops Lab

1. A Java application was developed to implement currency, distance, and time converters using packages. Packages were created called "converter", "distance", and "time" with class files Dollar.java, Distance.java, and Time.java respectively. 2. The packages were compiled and a main class "Converter" was written in a separate directory to access and use the packages. 3. Based on the user's choice, the appropriate conversion method like currency conversion, distance conversion or time conversion was called.

Uploaded by

Rogith M
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

VELAMMAL INSTITUTE OF TECHNOLOGY

Velammal Knowledge Park, Panchetti

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

ODD SEMESTER LAB RECORD

ACADEMIC YEAR (2020-2021)

REGULATION- 2017

CS8383 – OBJECT ORIENTED PROGRAMMING LAB

Name of the Student : SATHISH KUMAR.S

Register No. : 113319104076

Department : Computer Science and Engineering

Name of Laboratory : Object Oriented Programming Lab

Lab Code : CS8383

Year / Semester : II/III


BONAFIDE CERTIFICATE

University Register. No.

This is to certify that this is a bonafide record work done by

Mr. / Miss. SATHISH KUMAR.S studying B.E

II year Computer Science and Engineering Department in the CS 8383- Object Oriented

Programming Laboratory for III semester.

Staff-in-charge Head of the Department

Submitted for the University practical examination held on at

Velammal Institute of Technology.

Internal Examiner External Examiner

1
TABLE OF CONTENTS

Sl. No. Date Experiment Name Page Signature


No.

1. 14.08.20 ELECTRICITY BILL 1

2. 28.08.20 CONVERSIONS USING PACKAGES 5

3. 04.09.20 SALARY SLIP OF AN EMPLOYEE 13

4. 11.09.20 STACK ADT IMPLEMENTATION 18

5. 25.09.20 STRING OPERATIONS USING ARRAYLIST 22

6. 09.10.20 ABSTRACT CLASS 25

7. 16.10.20 USER DEFINED EXCEPTION HANDLING 27

8. 06.11.20 FILE OPERATIONS 29

9. 13.11.20 MULTITHREADING APPLICATION 31

FIND MAXIMUM VALUE USING A GENERIC


10. 27.11.20 34
FUNCTION

CALCULATOR USING EVENT_DRIVEN


11. 04.12.20 36
PROGRAMMING PARADIGM

2
Ex.No: 1 ELECTRICITY BILL

Aim:
Develop a Java application to generate Electricity bill by considering domestic and
commercial connection.

Algorithm:

1. Create a class called “ElectricityBill”, ”EBill_domestic”, and “EBill_commercial” with


specified members.
2. Computer domestic bill amount using class ”EBill_domestic”.
3. Computer commercial bill amount using class ”EBill_commercial”.
4. Write main method using “ElectricityBill” class.
5. Compile and Execute the class “ElectricityBill”, and generate the appropriate output.

Program:
// Java Program to Calculate Electricity Bill
import java.util.Scanner;

public class ElectricityBill


{
private static Scanner sc;
private static intUnits,P_reading,C_reading;
private static double Total_Amount;
private static String Cons_name,Conn_type;

public static void main(String[] args)


{
sc = new Scanner(System.in);

System.out.println("\n Enter the Consumer name :\t ");


Cons_name = sc.nextLine();
System.out.println("\n Enter the Connection Type(domestic/commercial) :");
Conn_type = sc.nextLine();
System.out.println("\n Enterpe and Previous Units that you Consumed :");
P_reading = sc.nextInt();
System.out.println("\n Enter the Current Units that you Consumed : ");
C_reading = sc.nextInt();
Units = C_reading - P_reading;

if(Conn_type.equals("domestic"))
{
Total_Amount = EBill_domestic (Units);
}

1
else if(Conn_type.equals("commercial"))
{
Total_Amount = EBill_comercial (Units);
}

System.out.println("\nConsumerName : "+Cons_name);
System.out.println("\nConnectionType : "+Conn_type);
System.out.println("\nPreviousReading : "+P_reading);
System.out.println("\nCurrentReading : "+C_reading);
System.out.println("\nConsumedUnits : "+Units);

System.out.println("\n Electricity Bill = " + Total_Amount);


}
public static double EBill_domestic(int Units)
{
double Amount, Total_Amount;
if (Units <= 100)
{
Amount = Units * 1.00;
}
else if (Units <= 200)
{
Amount = Units * 2.50;
}
else if (Units <= 500)
{
Amount = Units * 4.00;
}
else
{
Amount = Units * 6.00;
}
return Amount;
}
public static double EBill_comercial(int Units)
{
double Amount, Sur_Charge, Total_Amount;
if (Units <= 100)
{
Amount = Units * 2.00;
}
else if (Units <= 200)
{
Amount = Units * 4.50;
}
else if (Units <= 500)

2
{
Amount = Units * 6.00;
}
else
{
Amount = Units * 7.00;
}
return Amount;
}
}

Output:

3
Result:

Thusa Java application to generate Electricity bill by considering domestic and commercial
connection was executed successfully.

4
Ex.No:2 CONVERSIONS USING PACKAGES

Aim:

Develop a java application to implement currency converter (Dollar to INR, EURO to INR, Yen
to INR and vice versa), distance converter (meter to KM, miles to KM and vice versa) , time
converter (hoursto minutes, seconds and vice versa) using packages.

Algorithm:
1. Create a package with a class file
2. Set the “classpath” from the directory from which you would like to access. It may be in a
different drive and directory. Let us call it as a target directory.
3. Write a program and use the file from the package.
Let us create a package called forest and place a class called Tiger in it. Access the
package from a different drive and directory.

Program:

Step 1: Create a package (coverter) and place Dollar.class in it.(Package Creation)


Let us assume C:\myjava is the current directory where we would like to create the package.
C:\myjava > notepad Dollar.java

//Dollar.java
package converter;
import java.util.*;

public class Dollar


{
public void Convert()
{
double inr,usd,doll;
System.out.println("\nDollar to INR");
Scanner in=new Scanner(System.in);
System.out.print("Enter INR to convert into USD : ");
inr=in.nextDouble();
System.out.print("Enter Current USD reate : ");
doll=in.nextDouble();
usd=inr/doll;
System.out.println("\n INR="+inr+"\n USD="+usd);
}
}

While create User Defined Packages Java, the order of statements is very important. The order
must be like this, else, compilation error.

5
1. Package statement
2. Import statement
3. Class declaration

Step 2: Compiling the package (coverter):

D:\myjava >javac -d . Dollar.java

The –d compiler option creates a new folder called converter and places the Dollarr.class in it.
The dot (.) is an operating system's environment variable that indicates the current directory. It is
an instruction to the OS to create a directory called converter and place the Dollar.class in it.

Step 3:Now finally, write a program from the target directory D:/myjava and access the package
as below: D:\myjava> notepad Compute.java

// Compute.java
import converter.Dollar;

public class Compute


{
public static void main(String s[])
{
Dollar d=new Dollar();
d.Convert();
}
}

Step 4:Compilation and execution of Compute.java as below:

D:\myjava>javacCompute.java
D:\myjava> java Compute

//For distance conversion

package distance;

import java.util.*;

public static void main(String args[])

Scanner sc=new Scanner(System.in);

6
Public void d()

double miles,km;

System.out.println(“Meters to km conversion:”);

System.out.println(“Enter the meters:”);

miles=sc.nextInt();

km=miles/1000;

System.out.println(“km;”+km);

System.out.println(“km to miles conversion:”);

km=sc.nextInt();

miles=km*1000;

System.out.println(“Meters:”+miles);

//For time conversion

package time

import java.util.*;

public class time

Scanner sc =new Scanner(System.in);

public void t()

double min,sec.hr;

7
System.out.println(“Enter the minutes:”);

min=sc.nextInt()

hr=min/60;

System.out.println(“Hour:”,+hr);

System.out.println(“Enter the hour:”);

hr=Sc.nextInt();

sec=hr*3600;

System.out.println(“Seconds:”,+sec);

//To import all the packages

import currency.*;

import distance.*;

import time.*;

class converter

public static void main(String args[])

int type;

Scanner i=new Scanner();

System.out.println(“Enter your choice:\n 1. Currency conversion \n 2. Distance conversion \n


3. Time conversion\n”);

type=i.nextInt();

currency s=new currency();

8
distance r=new distance();

time q=new time();

switch(type)

Case 1:

s.c();

break;

case 2:

r.d();

break;

case 3:

q.t();

break;

Output:

9
10
11
Result:

Thus a java application to implement currency converter, distance converter, time converter
using packages was executed successfully.

12
Ex.No:3 SALARY SLIP OF AN EMPLOYEE

Aim:

ToDevelop a Java application to generate Employee Pay slip for using Inheritance.

Algorithm:
1. Create a class called Employee with Emp_name, Emp_id, Address, Mail_id, Mobile_no as
members and compute the payslip
2. Extends the Employee class for further classes called Programmer, Assistant Professor,
Associate Professor and Professor
3. Create class called Pay slip and generate Pay slip according to the position of the Employee.
Program:
// Payslip.java

import java.util.Scanner;
class Employee
{
String Emp_name,Mail_id,Address,Emp_id, Mobile_no;
double BP,GP,NP,DA,HRA,PF,CF;
Scanner get = new Scanner(System.in);
Employee()
{
System.out.println("Enter Name of the Employee:");
Emp_name = get.nextLine();
System.out.println("Enter Address of the Employee:");
Address = get.nextLine();
System.out.println("Enter ID of the Employee:");
Emp_id = get.nextLine();
System.out.println("Enter Mobile Number:");
Mobile_no = get.nextLine();
System.out.println("Enter E-Mail ID of the Employee :");
Mail_id = get.nextLine();
}
void display()
{
System.out.println("Employee Name: "+Emp_name);
System.out.println("Employee Address: "+Address);
System.out.println("Employee ID: "+Emp_id);
System.out.println("Employee Mobile Number: "+Mobile_no);

13
System.out.println("Employee E-Mail ID"+Mail_id);
DA=BP*0.97;
HRA=BP*0.10;
PF=BP*0.12;
CF=BP*0.01;
GP=BP+DA+HRA+PF;
NP=GP-PF-CF;

System.out.println("Basic Pay :"+BP);


System.out.println("Dearness Allowance : "+DA);
System.out.println("House Rent Allowance :"+HRA);
System.out.println("Provident Fund :"+PF);
System.out.println("Club Fund :"+CF);

System.out.println("Gross Pay :"+GP);


System.out.println("Net Pay :"+NP);
}
}
class Programmer extends Employee
{
Programmer()
{
System.out.println("Enter Basic pay of the Programmer:");
BP = get.nextFloat();
}
void display()
{
System.out.println("=============================="+"\n"+"Programmar Pay
Slip"+"\n"+"=============================="+"\n");
super.display();
}
}
class Assistant_Professor extends Employee
{
Assistant_Professor()
{
System.out.println("Enter Basic pay of the Assistant Professor:");
BP = get.nextFloat();
}
void display()

14
{
System.out.println("=============================="+"\n"+"Assistant Professor
Pay Slip"+"\n"+"=============================="+"\n");
super.display();
}
}
class Associate_Professor extends Employee
{
Associate_Professor()
{
System.out.println("Enter Basic pay of the Professor:");
BP = get.nextFloat();
}
void display()
{
System.out.println("=============================="+"\n"+"Associate Professor
Pay Slip"+"\n"+"=============================="+"\n");
super.display();
}
}

class Professor extends Employee


{
Professor()
{
System.out.println("Enter Basic pay of the Professor:");
BP = get.nextFloat();
}
void display()
{
System.out.println("=============================="+"\n"+"Professor Pay
Slip"+"\n"+"=============================="+"\n");
super.display();
}
}

class Payslip
{
public static void main(String args[])
{

15
String pos;
Scanner get = new Scanner(System.in);
System.out.println("\nEnter Employee Position :");
pos=get.nextLine();

if(pos.equals("Programmer")||pos.equals("programmer"))
{
Programmer p=new Programmer();
p.display();
}

if(pos.equals("AP")||pos.equals("ap"))
{
Assistant_Professor AP=new Assistant_Professor();
AP.display();
}

if(pos.equals("ASSOCIATE")||pos.equals("associate"))
{
Associate_Professor ASP=new Associate_Professor();
ASP.display();
}

if(pos.equals("PROFESSOR")||pos.equals("professor"))
{
Professor PR=new Professor();
PR.display();
}
}
}

Output:

16
Result:

Thus a Java applicationtodevelop and to generate Employee Pay slip for using Inheritance was
executed successfully.

Ex.No: 4 STACK ADT IMPLEMENTATION

17
Aim:

To write the java program for ADT stack using interface.

Algorithm:

1: Start the program


2: Create an interface which consists of three methods namely PUSH, POP and
DISPLAY
3: Create a class which implements the above interface to implement the concept
of stack through Array
4: Define all the methods of the interface to push any element, to pop the to
element and to display the elements present in the stack.
5: Create another class which implements the same interface to implement
the concept of stack through linked list.
6: Repeat STEP 4 for the above said class also.
7: In the main class, get the choice from the user to choose whether
array implementation or linked list implementation of the stack.
8: Call the methods appropriately according to the choices made by the user in the
previous step.
9: Repeat step 6 and step 7 until the user stops his/her execution
10: Stop the program

Program:
import java.lang.*;
import java.io.*;
import java.util.*;
interface Mystack
{
int n=10;
public void pop();
public void push();
public void peek();
public void display();
}
class Stackimp implements Mystack
{
intstack[]=new int[n];
int top=-1;
public void push()

18
{
try{
DataInputStream dis=new DataInputStream(System.in);
if(top==(n-1))
{
System.out.println("overflow");
return;
}
else
{
System.out.println("enter element");
intele=Integer.parseInt(dis.readLine());
stack[++top]=ele;
}
}
catch(Exception e)
{
System.out.println("e");
}
}
public void pop()
{
if(top<0)
{
System.out.println("underflow");
return;
}
else
{
int popper=stack[top];
top--;
System.out.println("popped element" +popper);
}
}
public void peek()
{
if(top<0)
{
System.out.println("underflow");
return;

19
}
else
{
int popper=stack[top];
System.out.println("popped element" +popper);
}
}
public void display()
{
if(top<0)
{
System.out.println("empty");
return;
}
else
{
String str=" ";
for(int i=0;i<=top;i++)
str=str+" "+stack[i];
System.out.println("elements are"+str);
}
}
}
class Stackadt
{
public static void main(String arg[])throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
Stackimpstk=new Stackimp();
intch=0;
do{
System.out.println("enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit");
ch=Integer.parseInt(dis.readLine());
switch(ch){
case 1:stk.push();
break;
case 2:stk.pop();
break;
case 3:stk.peek();
break;

20
case 4:stk.display();
break;
case 5:System.exit(0);
}
}while(ch<=5);
}
}
Output:

Result:

Thus the Java program for ADT stack using interface was executed successfully.

Ex.No:5 STRING OPERATIONS USING ARRAYLIST

21
Aim:
To Write a Java program to perform basic string operations using ArrayList.

Algorithm:

Step 1:Create an two ArrayList named obj and MySortStrings as String type.
Step 2:insert the String elements at last one by one and display the Arraylistobj elements.
Step 3:Add elements to the existing ArrayList at a specific position using add() method.
Step 4:Using remove() method we can remove elements from the Arraylist.
Step 5:To search a specific element,get the input of the element to search.
Step 6:UsingindexOf() method get the position of the element and if element found display the
String, else print element not found and display the updated array.
Step 7:Get the element starting letter from the user and find the position using get() method then
store in the new ArrayListMySortStrings.
Step 8:Display the new Arraylist.
Step 9:Stop the program execution.

Program:

import java.util.*;
public class ArrayListExample {
public static void main(String args[]) {
ArrayList<String>obj = new ArrayList<String>();
ArrayList<String>MySortStrings =new ArrayList<String>();
Scanner sc=new Scanner(System.in);
obj.add("Ajeet");
obj.add("Harry");
obj.add("Chaitanya");
obj.add("Steve");
obj.add("Anuj");
System.out.println("Currently the array list has following elements:"+obj);
obj.add(0, "Rahul");
obj.add(1, "Justin");
obj.remove("Chaitanya");
obj.remove("Harry");
System.out.println("Current array list is:"+obj);
obj.remove(1);
System.out.println("Enter the string to search");
String str=sc.nextLine();
intpos = obj.indexOf(str);
if(pos>0)
System.out.println("element is present "+obj.get(pos));
else
System.out.println("element not present in the arraylist");
System.out.println("Current array list is:"+obj);

22
System.out.println("enter the elements to search by giving first letter");
String str1=sc.nextLine();
for(int i=0;i<obj.size();i++)
{
if(obj.get(i).startsWith(str1.toUpperCase()))
{
MySortStrings.add(obj.get(i));
}
}
System.out.println(MySortStrings);
}
}

Output:

23
Result:

Thus a java program to perform basic string operations using ArrayList was executed successfully.

24
Ex.No:6 ABSTRACT CLASS

Aim:
To Write a Java program using abstract class and inheritance.

Algorithm:

Step 1:Create an abstract class called shape and assign value to the variables a and b.
Step 2:declare an method print_area() in the abstract class.
Step 3:Create three classes rectangle, triangle and circle.
Step 4:In each class inherit the base abstract class.
Step 5:Implementprint_area() method and perform area calculation for each shape.
Step 6:display each class area.
Step 7:Stop the program execution.

Program:
abstract class shape
{
int a=3,b=4;
abstract public void print_area();
}
class rectangle extends shape
{
public int area_rect;
public void print_area()
{
area_rect=a*b;
System.out.println("The area of rectangle is:"+area_rect);
}
}
class triangle extends shape
{
intarea_tri;
public void print_area()
{
area_tri=(int) (0.5*a*b);
System.out.println("The area of triangle is:"+area_tri);
}
}
class circle extends shape
{
intarea_circle;

public void print_area()


{

25
area_circle=(int) (3.14*a*a);
System.out.println("The area of circle is:"+area_circle);
}
}
public class JavaApplication3 {

public static void main(String[] args) {


rectangle r=new rectangle();
r.print_area();
triangle t=new triangle();
t.print_area();
circle r1=new circle();
r1.print_area();
}
}

Output:

Result:

Thus a java program using abstract class and inheritance was executed successfully.

26
Ex.No:7 USER DEFINED EXCEPTION HANDLING

Aim:
To write a Java program to implement user defined exception.

Algorithm:

Step 1:Create a class MyException that extends inbuilt class Exception.


Step 2:In main class call the method sum() to perform summation operation if positive.
Step 3:else call user defined exception to print the error message.
Step 4:Stop the program execution.

class MyException extends Exception


{
private int ex;
MyException(int a)
{
ex=a;
}
public String toString()
{
return "MyException[" + ex +"] is less than zero";
}
}
class Test
{
static void sum(inta,int b) throws MyException
{
if(a<0)
{
throw new MyException(a);
}
else
{
System.out.println(a+b);
}
}
public static void main(String[] args)
{
try
{
sum(-10, 10);
}
catch(MyException me)
{

27
System.out.println(me);
} }}

Output:

Result:

Thus a Java program to implement user defined exception was executed successfully.

28
Ex.No:8 FILE OPERATIONS

Aim:

To write a Java Program to perform file handling operations.

Algorithm:

Step 1:Import the necessary packages.


Step 2:Get the input of the File.
Step 3:Using File class create a object to perform basic operations in File.
Step 4:Use the inbuilt functions such as getName(),getPath(),exists(),isHidden() etc.,to display
the details about the input file.
Step 5:Stop the program execution.

Program:

import java.util.*;
import java.io.*;
class FileDemo
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
String s=input.nextLine();
File f1=new File(s);
long t=f1.lastModified();
Date d=new Date(t);
System.out.println("File Name:"+f1.getName());
System.out.println("Path:"+f1.getPath());
System.out.println("Abs Path:"+f1.getAbsolutePath());
System.out.println("Parent:"+f1.getParent());
System.out.println("This file is:"+(f1.exists()?"Exists":"Does not exists"));
System.out.println("Is file:"+f1.isFile());
System.out.println("Is Directory:"+f1.isDirectory());
System.out.println("Is Readable:"+f1.canRead());
System.out.println("IS Writable:"+f1.canWrite());
System.out.println("Is Absolute:"+f1.isAbsolute());
System.out.println("File Last Modified:"+d);
System.out.println("File Size:"+f1.length()+"bytes");
System.out.println("Is Hidden:"+f1.isHidden());
}
}

29
Output:

Result:

Thus a Java Program to perform file handling operations was executed successfilly.

30
Ex.No:9 MULTITHREADING APPLICATION

Aim:

To write a java program to implement multi threaded application.

Algorithm:

Step 1: Import the necessary package in the program.


Step 2: Create a class A and extends inbuilt Thread Class.
Step 3:Generate Random number using Random class and check whether the number is even or
odd.
Step 4:if number is even call first Thread to run even method in even class and print the square
of the number.
Step 5:else call odd method in odd class and print cube of the number.
Step 6:Stop the program execution.

Program:
import java.util.*;
class even implements Runnable
{
public int x;
public even(int x)
{
this.x = x;
}
public void run()
{
System.out.println("New Thread "+ x +" is EVEN and Square of " + x + " is: " + x * x);
}
}
class odd implements Runnable
{
public int x;
public odd(int x)
{
this.x = x;
}
public void run()
{

31
System.out.println("New Thread "+ x +" is ODD and Cube of " + x + " is: " + x * x * x);
}
}
class A extends Thread
{
public void run()
{
intnum = 0;
Random r = new Random();
try {
for (int i = 0; i < 5; i++)
{
num = r.nextInt(100);
System.out.println("Main Thread and Generated Number is " + num);
if (num % 2 == 0) {
Thread t1 = new Thread(new even(num));
t1.start();
}
else
{
Thread t2 = new Thread(new odd(num));
t2.start();
}
Thread.sleep(1000);
System.out.println("--------------------------------------");
}
} catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
public class JavaProgram5
{
public static void main(String[] args)
{
A a = new A();
a.start();
}
}

32
Output:

Result:

Thus a java program to implement multi threaded application was executed successfully.

33
Ex.No:10 FIND MAXIMUM VALUE USING A GENERIC FUNCTION

Aim:
To Write a Java program to find maximum value from the given type of elements using generic
functions.

Algorithm:
Step 1:Create a generic method maximum to accept any type of elements.
Step 2:UsingCompareTo method to find the maximum value from the given elements and return
to the value to main.
Step 3:Pass the arguments as integer,decimal and string type to the maximum function.
Step 4:The method returns the maximum value to the main to print.
Step 5:Stop the program execution.

Program:
public class MaximumTest
{
// determines the largest of three Comparable objects
public static <T extends Comparable<T>> T maximum(T x, T y, T z)
{
T max = x; // assume x is initially the largest
if ( y.compareTo( max ) > 0 ){
max = y; // y is the largest so far
}
if ( z.compareTo( max ) > 0 ){
max = z; // z is the largest now
}
return max; // returns the largest object
}
public static void main( Stringargs[] )
{
System.out.printf( "Max of %d, %d and %d is %d\n\n",
3, 4, 5, maximum( 3, 4, 5 ) );

System.out.printf( "Maxm of %.1f,%.1f and %.1f is %.1f\n\n",


6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ) );

System.out.printf( "Max of %s, %s and %s is %s\n","pear",


"apple", "orange", maximum( "pear", "apple", "orange" ) );
}}

34
Output:

Result:

Thus a Java program to find maximum value from the given type of elements using generic
functions was executed successfully.

35
Ex.No:11 CALCULATOR USING EVENT_DRIVEN PROGRAMMING PARADIGM

AIM:
To write a java program to implement the scientific calculator using event
driven programming

ALGORITHM:

1. Create the class scientific calculator .Define and declare its variables.
2. Using scientific calculator constructor create buttons that are in the scientific calculator.
3. Using actionPerformed() method define the function that has to be done when the
corresponding buttons are pressed.
4. In the main function create the objects for the class scientific calculator and then using that
objects set the title for the program as scientific calculator and then press the buttons in the
calculator to get the results which you want

PROGRAM:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
public class ScientificCalculator extends JFrame implements ActionListener
{
JTextFieldtfield;

double temp,temp1,result,a,ml;
static double m1,m2;
int k=1,x=0,y=0,z=0;
charch;
JButton
b1,b2,b3,b4,b5,b6,b7,b8,b9,zero,clr,pow2,pow3,exp,fac,plus,min,div,log, rec,mul,eq,addsub,do
t,mr,mc,mp,mm,sqrt,sin,cos,tan;
Container cont;
JPaneltextpanel,buttonpanel;
ScientificCalculator()
{
cont=getContentPane();
cont.setLayout(new BorderLayout());
JPaneltextpanel=new JPanel();
tfield=new JTextField(25);
tfield.setHorizontalAlignment(SwingConstants.RIGHT);
tfield.addKeyListener(new KeyAdapter()
{
public void keyTyped(KeyEventkeyevent)

36
{
char c=keyevent.getKeyChar();
if(c>='0'&&c<='9')
{
}
else
{
keyevent.consume();
}
}
});
textpanel.add(tfield);
buttonpanel=new JPanel();
buttonpanel.setLayout(new GridLayout(8,4,2,2));
boolean t=true;
mr=new JButton("MR");
buttonpanel.add(mr);
mr.addActionListener(this);
mc=new JButton("MC");
buttonpanel.add(mc);
mc.addActionListener(this);
mp=new JButton("M+");
buttonpanel.add(mp);
mp.addActionListener(this);
mm=new JButton("M-");
buttonpanel.add(mm);
mm.addActionListener(this);
b1=new JButton("1");
buttonpanel.add(b1);
b1.addActionListener(this);
b2=new JButton("2");
buttonpanel.add(b2);
b2.addActionListener(this);
b3=new JButton("3");
buttonpanel.add(b3);
b3.addActionListener(this);
b4=new JButton("4");
buttonpanel.add(b4);
b4.addActionListener(this);
b5=new JButton("5");
buttonpanel.add(b5);
b5.addActionListener(this);
b6=new JButton("6");
buttonpanel.add(b6);
b6.addActionListener(this);
b7=new JButton("7");

37
buttonpanel.add(b7);
b7.addActionListener(this);
b8=new JButton("8");
buttonpanel.add(b8);
b8.addActionListener(this);
b9=new JButton("9");
buttonpanel.add(b9);
b9.addActionListener(this);
zero=new JButton("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=new JButton("/");
buttonpanel.add(div);
div.addActionListener(this);
addsub=new JButton("+/-");
buttonpanel.add(addsub);
addsub.addActionListener(this);
dot=new JButton(".");
buttonpanel.add(dot);
dot.addActionListener(this);
eq=new JButton("=");
buttonpanel.add(eq);
eq.addActionListener(this);
rec=new JButton("1/x");
buttonpanel.add(rec);
rec.addActionListener(this);
sqrt=new JButton("Sqrt");
buttonpanel.add(sqrt);
sqrt.addActionListener(this);
log=new JButton("log");
buttonpanel.add(log);
log.addActionListener(this);
sin=new JButton("SIN");
buttonpanel.add(sin);
sin.addActionListener(this);
cos=new JButton("COS");
buttonpanel.add(cos);

38
cos.addActionListener(this);
tan=new JButton("TAN");
buttonpanel.add(tan);
tan.addActionListener(this);
pow2=new JButton("x^2");
buttonpanel.add(pow2);
pow2.addActionListener(this);
pow3=new JButton("X^3");
buttonpanel.add(pow3);
pow3.addActionListener(this);
exp=new JButton("Exp");
buttonpanel.add(exp);
exp.addActionListener(this);
fac=new JButton("n!");
buttonpanel.add(fac);
fac.addActionListener(this);
clr=new JButton("AC");
buttonpanel.add(clr);
clr.addActionListener(this);
cont.add("Center",buttonpanel);
cont.add("North",textpanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
String s=e.getActionCommand();
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

39
{
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");
}
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"))

40
{
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
{

41
tfield.setText("");
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("AC"))
{
tfield.setText("");
x=0;y=0;
z=0;
}
if(s.equals("log"))
{
if(tfield.getText().equals(""))
{
tfield.setText("");
}
else
{
a=Math.log(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText()+a);

}
}
if(s.equals("1/x"))
{
if(tfield.getText().equals(""))
{
tfield.setText("");
}
else
{

42
a=1/(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText()+a);
}
}
if(s.equals("Exp"))
{
if(tfield.getText().equals(""))
{
tfield.setText("");
}
else
{
a=Math.exp(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText()+a);
}
}
if(s.equals("x^2"))
{
if(tfield.getText().equals(""))
{
tfield.setText("");
}
else
{
a=Math.pow(Double.parseDouble(tfield.getText()),2);
tfield.setText("");
tfield.setText(tfield.getText()+a);
}
}
if(s.equals("X^3"))
{
if(tfield.getText().equals(""))
{
tfield.setText("");
}
else
{
a=Math.pow(Double.parseDouble(tfield.getText()),3);
tfield.setText("");
tfield.setText(tfield.getText()+a);
}
}
if(s.equals("+/-"))
{

43
if(x==0)
{
tfield.setText("-"+tfield.getText());
x=1;
}
else
{
tfield.setText(tfield.getText());
}
}
if(s.equals("."))
{
if(y==0)
{
tfield.setText(tfield.getText()+".");
y=1;
}
else
{
tfield.setText(tfield.getText());
}
}
if(s.equals("+"))
{
if(tfield.getText().equals(""))
{
tfield.setText("");
temp=0;
ch='+';
}
else
{
temp=Double.parseDouble(tfield.getText());
tfield.setText("");
ch='+';
y=0;x=0;
}
tfield.requestFocus();
}
if(s.equals("-"))
{
if(tfield.getText().equals(""))
{
tfield.setText("");
temp=0;
ch='-';

44
}
else
{
y=0;x=0;
temp=Double.parseDouble(tfield.getText());
tfield.setText("");
ch='-';
}
tfield.requestFocus();
}
if(s.equals("/"))
{
if(tfield.getText().equals(""))
{
tfield.setText("");
temp=1;
ch='/';
}
else
{
y=0;x=0;
temp=Double.parseDouble(tfield.getText());
ch='/';
tfield.setText("");
}
tfield.requestFocus();
}
if(s.equals("*"))
{
if(tfield.getText().equals(""))
{
tfield.setText("");
temp=1;
ch='*';
}
else
{
y=0;x=0;
temp=Double.parseDouble(tfield.getText());
ch='*';
tfield.setText("");
}
tfield.requestFocus();
}
if(s.equals("MC"))
{

45
ml=0;
tfield.setText("");
}
if(s.equals("MR"))
{
tfield.setText("");
tfield.setText(tfield.getText()+ml);
}
if(s.equals("M+"))
{
if(k==1)
{
ml=Double.parseDouble(tfield.getText());
k++;
}
else
{
ml+=Double.parseDouble(tfield.getText());
tfield.setText(""+ml);
}
}
if(s.equals("M-"))
{
if(k==1)
{
ml=Double.parseDouble(tfield.getText());
k++;
}
else
{
ml-=Double.parseDouble(tfield.getText());
tfield.setText(""+ml);
}
}
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);

46
}
}
if(s.equals("SIN"))
{
if(tfield.getText().equals(""))
{
tfield.setText("");
}
else
{
a=Math.sin(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("TAN"))
{
if(tfield.getText().equals(""))
{
tfield.setText("");
}
else
{
a=Math.tan(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText()+a);
}
}
if(s.equals("="))
{
if(tfield.getText().equals(""))
{
tfield.setText("");

47
}
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("");
tfield.setText(tfield.getText()+result);
z=1;
}
}
if(s.equals("n!"))
{
if(tfield.getText().equals(""))
{
tfield.setText("");
}
else
{
a=fact(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText()+a);
}
tfield.requestFocus();
}
}
double fact(double x)
{
/*int er=0;
if(x>0)
{
er=20;
return 0;

48
}*/
double i,s=1;
for(i=2;i<=x;i+=1.0)
s*=i;
return s;
}
public static void main(String srgs[])
{
/*try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookA
ndFeel");
}
catch(Exception e)
{
/*/ ScientificCalculator f;
f=new ScientificCalculator();
f.setTitle("Scientific calculator");
f.pack();
f.setVisible(true);
/* } */
}
}

Output:

Result:

Thus a java program to implement the scientific calculator using event driven programming
was executed successfully.

49
50

You might also like