Oops Lab Manual
Oops Lab Manual
LABORATORY MANUAL
SUB.CODE : CS3381
LABORATORY
REGULATION: 2021
SEMSETER: III
1
SYLLABUS
LIST OF EXPERIMENTS:
2
SOLVE PROBLEMS BY USING SEQUENTIAL SEARCH, BINARY
EX NO :1 SEARCH, AND QUADRATIC SORTING ALGORITHMS
(SELECTION, INSERTION)
Aim:
To Solve problems by using sequential search, binary search, and quadratic sorting
algorithms (Selection, insertion).
1. Sequential Search:
Algorithm:
1. Let the element to be search be x.
2. Start from the leftmost element of arr[] and one by one compare x with each
element of arr[].
3. If x matches with an element then return that index.
4. If x doesn’t match with any of elements then return -1.
Program:
class GFG {
public static int search(int arr[], int x)
{
int n = arr.length;
for (int i = 0; i < n; i++)
{ if (arr[i] == x)
return i;
}
return -1;
}
public static void main(String args[])
{
int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
int result = search(arr, x);
if (result == -1)
System.out.print("Element is not present in array");
else
System.out.print("Element is present" + " at index " + result);
3
}
}
Output:
5
int result = ob.binarySearch(arr, x);
if (result == -1)
System.out.println("Element not present");
else
System.out.println("Element found at index " + result);
}
}
Output:
3. Insertion Sort:
Algorithm:
1. Iterate from arr[1] to arr[N] over the array.
2. Compare the current element (key) to its predecessor.
3. If the key element is smaller than its predecessor, compare it to the elements before.
4. Move the greater elements one position up to make space for the swapped element.
Program:
class InsertionSort {
void sort(int
arr[])
{
int n = arr.length;
for (int i = 1; i < n; ++i)
{
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;}
}
6
7
static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main(String args[])
{
int arr[] = { 12, 11, 13, 5, 6 };
InsertionSort ob = new InsertionSort();
ob.sort(arr);
printArray(arr);
}
}
Output:
5 6 11 12 13
4. Selection Sort:
Algorithm:
1. Initialize minimum value(min_idx) to location 0
2. Traverse the array to find the minimum element in the array
3. While traversing if any element smaller than min_idx is found then swap both the
values.
4. Then, increment min_idx to point to next element
5. Repeat until array is sorted
Program:
class SelectionSort
{
void sort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n-1; i++)
{
8
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}
public static void main(String args[])
{
SelectionSort ob = new SelectionSort();
int arr[] = {64,25,12,22,11};
ob.sort(arr);
System.out.println("Sorted array");
ob.printArray(arr);
}
}
Output:
Sorted array:
11 12 22 25 64
Result:
Thus the problems by using sequential search, binary search, and quadratic sorting
algorithms (Selection, insertion) have been successfully executed.
9
EX NO :2 DEVELOP STACK AND QUEUE DATA STRUCTURES USING
CLASSES AND OBJECTS.
Aim:
To develop stack and queue data structures using classes and objects.
1. Stack:
Algorithm:
Algorithm Push
():
begin
if stack is full
return
end if
else
increment top
stack[top] assign value
end else
end
Algorithm Pop ():
begin
if stack is empty
return
endif
else
store value of stack[top]
decrement top
return value
end else
end
10
Program:
package ex2;
class stack
{
public int maxSize;
public int stackArray[];
private int top;
public stack(int a)
{
maxSize=a;
stackArray=new
int[a]; top=-1;
}
public void push(int item)
{
if(top==maxSize-1)
{
System.out.println("stack overflow! cannot insert");
}
else
{
top++;
stackArray[top]=item;
}
}
public void pop()
{
if(top==-1)
{
System.out.println("stack is empty");
}
else
{
System.out.println("element popped:" +stackArray[top]);
top--;
}
}
public int peek()
{
return stackArray[top];
}
public static void main(String args[])
{
stack stack=new stack(4);
stack.push(10);
System.out.println("elemented inserted:"+stack.peek());
stack.push(20);
System.out.println("el inserted:"+stack.peek());
stack.push(30);
System.out.println("elemented inserted:"+stack.peek());
stack.push(40);
11
System.out.println("elemented inserted:"+stack.peek());
stack.pop();
}
}
Output:
12
removed value of queue[front]
decrement front
end else
end
Program:
import java.util.*;
public class Queue
{
int arr[], front, rear, cap, n1;
// Queue constructor
Queue(int n)
{
arr = new int[n];
cap = n;
front = 0;
rear = -1;
n = 0;
}
// dequeue function for removing the front element
public void dequeue()
{
// check for queue underflow
if (isEmpty())
{
System.out.println("No items in the queue,cannot delete");
System.exit(1);
}
else
} System.out.println("Queue Is Not Empty");
1--;
}
14
Output:
Case : 1
10 insert to queue
20 insert to queue
30 insert to queue
40 insert to queue
Case: 2
10 delete from queue
Result:
Thus the problems for developing stack and queue data structures using classes and
objects have been successfully executed.
15
DEVELOP A JAVA APPLICATION WITH AN EMPLOYEE CLASS
EX NO :3 WITH MEMBERS FOR GENERATE PAY SLIP USING
INHERITANCE
Aim:
To develop a java application with an employee class with members for generate pay
slip using inheritance.
Algorithm:
1. Create the class employee with name, Empid, address, mailid, mobileno as members.
2. Inherit the classes programmer, asstprofessor,associateprofessor and professor
from employee class.
3. Add Basic Pay (BP) as the member of all the inherited classes.
4. Calculate DA as 97% of BP, HRA as 10% of BP, PF as 12% of BP, Staff club fund as
0.1% of BP
5. Calculate gross salary and net salary.
6. Generate payslip for all categories of employees.
7. Create the objects for the inherited classes and invoke the necessary methods
to display the Payslip.
Program:
import java.util.*;
class employee
{
int empid; long
mobile;
String name, address, mailid;
Scanner get = new Scanner(System.in); void
getdata()
{
System.out.println("Enter Name of the Employee"); name =
get.nextLine();
System.out.println("Enter Mail id"); mailid
= get.nextLine();
System.out.println("Enter Address of the Employee:"); address
= get.nextLine();
16
System.out.println("Enter employee id ");
empid = get.nextInt();
System.out.println("Enter Mobile Number");
mobile = get.nextLong();
}
void display()
{
System.out.println("Employee Name: "+name);
System.out.println("Employee id : "+empid);
System.out.println("Mail id : "+mailid);
System.out.println("Address: "+address);
System.out.println("Mobile Number:
"+mobile);
}
}
class programmer extends employee
{
double salary,bp,da,hra,pf,club,net,gross;
void getprogrammer()
{
System.out.println("Enter basic
pay"); bp = get.nextDouble();
}
void calculateprog()
{
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
System.out.println("************************************************");
System.out.println("PAY SLIP FOR PROGRAMMER");
System.out.println("************************************************");
17
System.out.println("Basic Pay:Rs"+bp);
18
System.out.println("DA:Rs"+da);
System.out.println("PF:Rs"+pf);
System.out.println("HRA:Rs"+hra);
System.out.println("CLUB:Rs"+club);
System.out.println("GROSS PAY:Rs"+gross);
System.out.println("NET PAY:Rs"+net);
}
}
class asstprofessor extends employee
{
double salary,bp,da,hra,pf,club,net,gross;
void getasst()
{
System.out.println("Enter basic
pay"); bp = get.nextDouble();
}
void calculateasst()
{
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
System.out.println("************************************************");
System.out.println("PAY SLIP FOR ASSISTANT PROFESSOR");
System.out.println("************************************************");
System.out.println("Basic Pay:Rs"+bp);
System.out.println("DA:Rs"+da);
System.out.println("HRA:Rs"+hra);
System.out.println("PF:Rs"+pf);
System.out.println("CLUB:Rs"+club);
System.out.println("GROSS PAY:Rs"+gross);
System.out.println("NET PAY:Rs"+net);
19
}
}
class associateprofessor extends employee
{
double salary,bp,da,hra,pf,club,net,gross;
void getassociate()
{
System.out.println("Enter basic
pay"); bp = get.nextDouble();
}
void calculateassociate()
{
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
System.out.println("************************************************");
System.out.println("PAY SLIP FOR ASSOCIATE PROFESSOR");
System.out.println("************************************************");
System.out.println("Basic Pay:Rs"+bp);
System.out.println("DA:Rs"+da);
System.out.println("HRA:Rs"+hra);
System.out.println("PF:Rs"+pf);
System.out.println("CLUB:Rs"+club);
System.out.println("GROSS PAY:Rs"+gross);
System.out.println("NET PAY:Rs"+net);
}
}
class professor extends employee
{
double salary,bp,da,hra,pf,club,net,gross;
void getprofessor()
20
{
System.out.println("Enter basic
pay"); bp = get.nextDouble();
}
void calculateprofessor()
{
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
System.out.println("************************************************");
System.out.println("PAY SLIP FOR PROFESSOR");
System.out.println("************************************************");
System.out.println("Basic Pay:Rs"+bp);
System.out.println("DA:Rs"+da);
System.out.println("HRA:Rs"+hra);
System.out.println("PF:Rs"+pf);
System.out.println("CLUB:Rs"+club);
System.out.println("GROSS PAY:Rs"+gross);
System.out.println("NET PAY:Rs"+net);
}
}
class salary
{
public static void main(String args[])
{
int choice,cont;
do
{
System.out.println("PAYROLL");
System.out.println(" 1.PROGRAMMER \t 2.ASSISTANT PROFESSOR \t
3.ASSOCIATE PROFESSOR \t 4.PROFESSOR ");
21
Scanner c = new Scanner(System.in);
choice=c.nextInt();
switch(choice)
{
case 1:
{
programmer p=new programmer();
p.getdata();
p.getprogrammer();
p.display();
p.calculateprog();
break;
}
case 2:
{
asstprofessor asst=new asstprofessor();
asst.getdata();
asst.getasst();
asst.display();
asst.calculateasst();
break;
}
case 3:
{
associateprofessor asso=new associateprofessor();
asso.getdata();
asso.getassociate();
asso.display();
asso.calculateassociate();
break;
}
case 4:
{
professor prof=new professor();
22
prof.getdata();
prof.getprofessor();
prof.display();
prof.calculateprofessor();
break;
}
}
System.out.println("Do u want to continue 0 to quit and 1 to continue ");
cont=c.nextInt();
}while(cont==1);
}
}
Output:
Result:
Thus the Java application has been created with employee class and pay slips are
generated for the employees with their gross and net salary using inheritance concepts
23
WRITE A JAVA PROGRAM TO CREATE AN ABSTRACT CLASS
EX NO :4
FOR CALCULATING AREA OF DIFFERENT SHAPE
Aim:
To write a java program to create abstract class for calculating area of different shape.
Algorithm:
1. Create an abstract class named shape that contains two integers and an empty method
named printarea().
2. Provide three classes named rectangle, triangle and circle such that each one of the
classes extends the class Shape.
3. Each of the inherited class from shape class should provide the implementation for
the method printarea().
4. Get the input and calculate the area of rectangle, circle and triangle.
5. In the shape class, create the objects for the three inherited classes and invoke the
methods and display the area values of the different shapes.
Program:
import java.util.*;
abstract class
shape
{
int a,b;
abstract public void printarea();
}
class rectangle extends shape
{
public int area_rect;
public void
printarea()
{
Scanner s=new Scanner(System.in);
System.out.println("enter the length and breadth of rectangle");
a=s.nextInt();
b=s.nextInt(); area_rect=a*b;
24
System.out.println("Length of rectangle "+a +"breadth of rectangle "+b);
25
System.out.println("The area ofrectangle is:"+area_rect);
}
}
class triangle extends shape
{
double area_tri;
public void
printarea()
{
Scanner s=new Scanner(System.in);
System.out.println("enter the base and height of triangle");
a=s.nextInt();
b=s.nextInt();
System.out.println("Base of triangle "+a +"height of triangle "+b);
area_tri=(0.5*a*b);
System.out.println("The area of triangle is:"+area_tri);
}
}
class circle extends shape
{
double area_circle;
public void
printarea()
{
Scanner s=new Scanner(System.in);
System.out.println("enter the radius of circle");
a=s.nextInt();
area_circle=(3.14*a*a);
System.out.println("Radius of
circle"+a);
System.out.println("The area of circle is:"+area_circle);
}
}
public class shapeclass
26
{
public static void main(String[] args)
{
27
rectangle r=new rectangle();
r.printarea();
triangle t=new triangle();
t.printarea();
circle r1=new circle();
r1.printarea();
}
}
Output:
Result:
Thus the Java program has been created with shape class and generated printarea() for
the class using abstract concepts and successfully implemented.
28
WRITE A JAVA PROGRAM TO CREATE INTERFACE FOR
EX NO :5
CALCULATING AREA OF DIFFERENT SHAPE
Aim:
To write a java program to create interface for calculating area of different shape.
Algorithm:
1. Create interface named shape that contains two integers and an empty method named
printarea().
2. Provide three classes named rectangle, triangle and circle such that each one of the
classes implements the interface Shape.
3. Each of the implemented class from shape interface should provide the
implementation for the method printarea().
4. Get the input and calculate the area of rectangle, circle and triangle.
5. In the shape interface, create the objects for the three inherited classes and invoke the
methods and display the area values of the different shapes.
Program:
import java.util.*;
interface shape
{
abstract public void printarea();
}
class rectangle implements shape
{
public int area_rect,a,b; public
void printarea()
{
Scanner s=new Scanner(System.in);
System.out.println("enter the length and breadth of rectangle");
a=s.nextInt();
b=s.nextInt(); area_rect=a*b;
System.out.println("Length of rectangle "+a +"breadth of rectangle "+b);
29
System.out.println("The area ofrectangle is:"+area_rect);
}
}
class triangle implements shape
{
double area_tri;
public int a,b;
public void printarea()
{
Scanner s=new Scanner(System.in);
System.out.println("enter the base and height of triangle");
a=s.nextInt();
b=s.nextInt();
System.out.println("Base of triangle "+a +"height of triangle "+b);
area_tri=(0.5*a*b);
System.out.println("The area of triangle is:"+area_tri);
}
}
class circle implements shape
{
double area_circle;
public int a;
public void printarea()
{
Scanner s=new Scanner(System.in);
System.out.println("enter the radius of circle");
a=s.nextInt();
area_circle=(3.14*a*a);
System.out.println("Radius of
circle"+a);
System.out.println("The area of circle is:"+area_circle);
}
}
public class shapeclass
30
{
31
public static void main(String[] args)
{
rectangle r=new rectangle();
r.printarea();
triangle t=new triangle();
t.printarea();
circle r1=new circle();
r1.printarea();
}
}
Output:
Result:
Thus the Java program has been created with shape interface and generated printarea()
for the interface using interface concepts and successfully implemented.
32
EX NO :6 IMPLEMENT EXCEPTION HANDLING AND CREATION OF USER
DEFINED EXCEPTIONS
Aim:
To write a java program for implementing user defined exceptions handling.
Algorithm:
1. Create a class which extends Exception class.
2. Create a constructor which receives the string as argument.
3. Get the amount as input from the user.
4. If the amount is negative, the exception will be generated.
5. Using the exception handling mechanism, the thrown exception is handled by the
catch construct.
6. After the exception is handled, the string “invalid amount “will be displayed.
7. If the amount is greater than 0 , the message “Amount Deposited “ will be displayed
Program:
import java.util.Scanner;
class NegativeAmtException extends Exception
{
String msg; NegativeAmtException(String
msg)
{
this.msg=msg;
}
public String toString()
{
return msg;
}
}
public class userdefined
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
33
System.out.print("Enter Amount:");
int a=s.nextInt();
try
{
if(a<0)
{
throw new NegativeAmtException("Invalid Amount");
}
System.out.println("Amount Deposited");
}
catch(NegativeAmtException e)
{
System.out.println(e);
}
}
}
Output:
Result:
Thus the Java program has been created for the user defined exception handling and
successfully implemented.
34
EX NO :7
IMPLEMENT A MULTI THREADED APPLICATION
Aim:
To write a java program for implementing multi-threaded application.
Algorithm:
1. Create a class even which implements first thread that computes .the square of the
number.
2. run() method implements the code to be executed when thread gets executed.
3. Create a class odd which implements second thread that computes the cube of the
number.
4. Create a third thread that generates random number. If the random number is even, it
displays the square of the number. If the random number generated is odd, it displays
the cube of the given number.
5. The Multithreading is performed and the task switched between multiple threads.
6. The sleep () method makes the thread to suspend for the specified time.
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
35
{
public int x;
public odd(int
x)
{
this.x = x;
}
public void run()
{
System.out.println("New Thread "+ x +" is ODD and Cube of " + x + " is: " + x * x *
x);
}
}
class A extends Thread
{
public void run()
{
int num = 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();
36
}
37
Thread.sleep(1000);
System.out.println(" ");
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
public class multithreadprog
{
public static void main(String[] args)
{
A a = new A();
a.start();
}
}
Output:
Result:
Thus the Java program has been created for the multi-threaded application and
successfully implemented.
38
EX NO :8
PROGRAM TO PERFORM FILE OPERATIONS
Aim:
To write a java program that reads a file name from the user, displays information about
whether the file exists, whether the file is readable, or writable, the type of file and the length of
the file in bytes.
Algorithm:
1. Create a class filedemo. Get the file name from the user.
2. Use the file functions and display the information about the file.
3. getName() displays the name of the file.
4. getPath() diplays the path name of the file.
5. getParent () -This method returns the pathname string of this abstract pathname’s
parent, or null if this pathname does not name a parent directory.
6. exists() – Checks whether the file exists or not.
7. canRead()-This method is basically a check if the file can be read.
8. canWrite()-verifies whether the application can write to the file.
9. isDirectory() – displays whether it is a directory or not.
10. isFile() – displays whether it is a file or not.
11. lastmodified() – displays the last modified information.
12. length()- displays the size of the file.
13. delete() – deletes the file
14. Invoke the predefined functions abd display the information about the file.
Program:
import java.io.*;
import java.util.*;
class filedemo
{
public static void main(String args[])
{
String filename;
Scanner s=new Scanner(System.in); System.out.println("Enter
the file name ");
39
filename=s.nextLine();
File f1=new File(filename);
System.out.println("*****************");
System.out.println("FILE INFORMATION");
System.out.println("*****************");
System.out.println("NAME OF THE FILE
"+f1.getName()); System.out.println("PATH OF THE FILE
"+f1.getPath());
System.out.println("PARENT"+f1.getParent());
if(f1.exists())
System.out.println("THE FILE EXISTS ");
else
System.out.println("THE FILE DOES NOT ExISTS ");
if(f1.canRead())
System.out.println("THE FILE CAN BE READ ");
else
System.out.println("THE FILE CANNOT BE READ ");
if(f1.canWrite())
System.out.println("WRITE OPERATION IS PERMITTED");
else
System.out.println("WRITE OPERATION IS NOT PERMITTED");
if(f1.isDirectory())
System.out.println("IT IS A DIRECTORY ");
else
System.out.println("NOT A DIRECTORY");
if(f1.isFile())
System.out.println("IT IS A FILE ");
else
System.out.println("NOT A FILE");
System.out.println("File last modified "+ f1.lastModified());
System.out.println("LENGTH OF THE FILE
"+f1.length()); System.out.println("FILE DELETED
"+f1.delete());
}
40
}
41
Output:
Result:
Thus the Java program has been created for the file operations and successfully
implemented.
42
DEVELOP AN APPLICATION FOR IMPLEMENTING GENERIC
EX NO :9
CLASS
Aim:
To write a java program for implementing generic class.
Algorithm:
1. Create a class Myclass to implement generic class and generic methods.
2. Get the set of the values belonging to specific data type.
3. Create the objects of the class to hold integer, character and double values.
4. Create the method to compare the values and find the maximum value stored in the
array.
5. Invoke the method with integer, character or double values. The output will be
displayed based on the data type passed to the method.
Program:
43
if(vals[i].compareTo(v) > 0)
v = vals[i];
return v;
}
}
class gendemo
{
public static void main(String args[])
{
int i;
Integer inums[]={10,2,5,4,6,1};
Character chs[]={'v','p','s','a','n','h'};
Double d[]={20.2,45.4,71.6,88.3,54.6,10.4};
MyClass<Integer> iob = new MyClass<Integer>(inums);
MyClass<Character> cob = new MyClass<Character>(chs);
MyClass<Double>dob = new MyClass<Double>(d);
System.out.println("Max value in inums: " + iob.max());
System.out.println("Min value in inums: " + iob.min());
System.out.println("Max value in chs: " + cob.max());
System.out.println("Min value in chs: " + cob.min());
System.out.println("Max value in chs: " + dob.max());
System.out.println("Min value in chs: " + dob.min());
}
}
Output:
Result:
Thus the Java program has been created for the generic class and successfully
implemented.
44
DEVELOP APPLICATIONS (CALCULATOR) USING JAVAFX
EX NO :10
CONTROLS, LAYOUTS AND MENUS (MINI PROJECT)
Aim:
To design a calculator as a mini project using event driven programming paradigm of
java with the following options
a) Decimal Manipulations
b) Scientific Manipulations
Algorithm:
1. import the swing packages and awt packages.
2. Create the class scientific calculator that implements action listener.
3. Create the container and add controls for digits , scientific calculations and
decimal Manipulations.
4. The different layouts can be used to lay the controls.
5. When the user presses the control, the event is generated and handled.
6. The corresponding decimal, numeric and scientific calculations are performed.
Program:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
public class ScientificCalculator extends JFrame implements ActionListener
{
JTextField tfield;
double temp, temp1, result, a;
static double m1, m2;
int k = 1, x = 0, y = 0, z = 0;
char ch;
JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, zero, clr, pow2, pow3, exp,
fac, plus, min, div, log, rec, mul, eq, addSub, dot, mr, mc, mp,
mm, sqrt, sin, cos,
tan;
Container cont;
JPanel textPanel, buttonpanel;
45
ScientificCalculator()
{
cont = getContentPane();
cont.setLayout(new BorderLayout());
JPanel textpanel = new JPanel();
tfield = new JTextField(25);
tfield.setHorizontalAlignment(SwingConstants.RIGHT);
tfield.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent keyevent)
{ char c = keyevent.getKeyChar();
if (c >= '0' && c <= '9') {
}
else
{
keyevent.consume();
}
}
});
textpanel.add(tfield);
buttonpanel = 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);
46
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");
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("-");
47
buttonpanel.add(min);
min.addActionListener(this);
mul = new JButton("*");
buttonpanel.add(mul);
mul.addActionListener(this);
div = new JButton("/");
div.addActionListener(this);
buttonpanel.add(div);
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);
cos.addActionListener(this);
tan = new JButton("TAN");
buttonpanel.add(tan);
48
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");
exp.addActionListener(this);
buttonpanel.add(exp);
fac = new JButton("n!");
fac.addActionListener(this);
buttonpanel.add(fac);
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() +
49
"1");
z = 0;
50
}
}
if (s.equals("2"))
{ if (z == 0) {
tfield.setText(tfield.getText() + "2");
}
else
{
tfield.setText("");
tfield.setText(tfield.getText() +
"2");
z = 0;
}
}
if (s.equals("3"))
{ if (z == 0) {
tfield.setText(tfield.getText() + "3");
}
else
{
tfield.setText("");
tfield.setText(tfield.getText() +
"3");
z = 0;
}
}
if (s.equals("4"))
{ if (z == 0) {
tfield.setText(tfield.getText() + "4");
}
else
{
tfield.setText("");
tfield.setText(tfield.getText() +
51
"4");
z = 0;
}
52
}
if (s.equals("5"))
{ if (z == 0) {
tfield.setText(tfield.getText() + "5");
}
else
{
tfield.setText("");
tfield.setText(tfield.getText() +
"5");
z = 0;
}
}
if (s.equals("6"))
{ if (z == 0) {
tfield.setText(tfield.getText() + "6");
}
else
{
tfield.setText("");
tfield.setText(tfield.getText() +
"6");
z = 0;
}
}
if (s.equals("7"))
{ if (z == 0) {
tfield.setText(tfield.getText() + "7");
}
else
{
tfield.setText("");
tfield.setText(tfield.getText() +
"7");
53
z = 0;
}
}
54
if (s.equals("8"))
{ if (z == 0) {
tfield.setText(tfield.getText() + "8");
}
else
{
tfield.setText("");
tfield.setText(tfield.getText() +
"8");
z = 0;
}
}
if (s.equals("9"))
{ if (z == 0) {
tfield.setText(tfield.getText() + "9");
}
else
{
tfield.setText("");
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() +
55
"0");
z = 0;
}
}
56
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
{
a = 1 / Double.parseDouble(tfield.getText());
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("Exp")) {
if (tfield.getText().equals("")) {
tfield.setText("");
}
else
57
{
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("+/-")) {
if (x == 0) {
tfield.setText("-" + tfield.getText());
x = 1;
}
else
58
{
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("-"))
{
59
if (tfield.getText().equals(""))
{
tfield.setText("");
temp = 0;
ch = '-';
}
else
{
x = 0;
y = 0;
temp = Double.parseDouble(tfield.getText());
tfield.setText("");
ch = '-';
}
tfield.requestFocus();
}
if (s.equals("/")) {
if (tfield.getText().equals(""))
{
tfield.setText("");
temp = 1;
ch = '/';
}
else
{
x = 0;
y = 0;
temp =
Double.parseDouble(tfield.getText()); ch =
'/';
tfield.setText("");
}
tfield.requestFocus();
}
60
if (s.equals("*")) {
61
if (tfield.getText().equals(""))
{
tfield.setText("");
temp = 1;
ch = '*';
}
else
{
x = 0;
y = 0;
temp =
Double.parseDouble(tfield.getText()); ch =
'*';
tfield.setText("");
}
tfield.requestFocus();
}
if (s.equals("MC"))
{
m1 = 0;
tfield.setText("");
}
if (s.equals("MR"))
{
tfield.setText("");
tfield.setText(tfield.getText() +
m1);
}
if (s.equals("M+"))
{
if (k == 1) {
m1 = Double.parseDouble(tfield.getText());
k++;
}
62
else
{
63
m1 += Double.parseDouble(tfield.getText());
tfield.setText("" + m1);
}
}
if (s.equals("M-"))
{
if (k == 1) {
m1 = Double.parseDouble(tfield.getText());
k++;
}
else
{
m1 -= Double.parseDouble(tfield.getText());
tfield.setText("" + m1);
}
}
if (s.equals("Sqrt"))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
}
else
{
a = Math.sqrt(Double.parseDouble(tfield.getText()));
tfield.setText("");
field.setText(tfield.getText() + a);
}
}
if (s.equals("SIN"))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
64
}
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("="))
{
65
if (tfield.getText().equals(""))
{
tfield.setText("");
}
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
66
{
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;
}
double i, s = 1;
for (i = 2; i <= x; i += 1.0)
s *= i;
return s;
}
public static void main(String args[])
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndF
eel");
}
catch (Exception e)
{
}
ScientificCalculator f = new ScientificCalculator();
f.setTitle("ScientificCalculator");
67
f.pack();
68
f.setVisible(true);
}
}
Output:
Result:
Thus the Java program has been created for the mini project using JavaFX and
successfully implemented.
69