Oops lab mannual java
Oops lab mannual java
EXNO:1(a)
DATE:
Java Program To Read Data Of Various Types Using Scanner Class
AIM:
To implement Java program to read data of various types using Scanner class.
PROCEDURE:
1. Import scanner class
2. Create object for class scanner.
3. Declare the object and initialize with predefined standard input object.
PROGRAM:
import java.util.Scanner;
public class ScannerDemo1
{ public static void main(String[] args)
Scanner sc = new Scanner(System.in);
System.out.println("enter your name");
String name = sc.nextLine();
System.out.println("enter your gender");
char gender = sc.next().charAt(0);
System.out.println("enter age");
int age = sc.nextInt();
System.out.println("enter mobile num");
long mobileNo = sc.nextLong();
System.out.println("enter cgpa");
double cgpa = sc.nextDouble();
System.out.println("Name: "+name);
System.out.println("Gender: "+gender);
System.out.println("Age: "+age);
System.out.println("Mobile Number: "+mobileNo);
System.out.println("CGPA: "+cgpa);
}
}
1
CS3381-OOP LAB GIT
OUTPUT:
RESULT:
Thus to implement Java program to read data of various types using Scanner class
was executed successfully.
2
CS3381-OOP LAB GIT
EXNO:2(a)
DATE:
SEQUENTIAL SEARCH
AIM:
To implement Java program for sequential search.
PROCEDURE:
Step 1: Set i to 1
Step 2: if i > n, then go to step 7
Step 3: if Ar[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit
PROGRAM:
import java.util.Scanner;
public class SequentialSearch {
public static void main(String[] args) {
int i , j, k, l = 0;
Scanner s = new Scanner(System.in);
System.out.println("Enter the size of array: ");
i = s.nextInt();
int[] ar = new int[i];
for(j = 0; j<i ; j++){
System.out.println("No "+ (j+1) + " = ");
ar[j] = s.nextInt();
}
System.out.println("Total Inserted list is : ");
for(j = 0; j<i ; j++){
System.out.println("No "+ (j+1)+"="+ ar[j]);
}
System.out.println("Enter the number which needs to find: ");
k = s.nextInt();
3
CS3381-OOP LAB GIT
RESULT:
Thus to implement Java program for sequential search was executed sucessfully.
4
CS3381-OOP LAB GIT
EXNO:2(b)
DATE:
BINARY SEARCH
AIM:
Java program for the implementation of recursive Binary Search.
PROCEDURE:
1. Binary search is one of the searching techniques applied when the input is sorted as
here we are focusing on finding the middle element that acts as a reference frame
whether to go left or right to it as the elements are already sorted.
2. The function returns an index of the search key, if it is contained in the array;
otherwise, (-(insertion point) – 1).
3. The insertion point is defined as the point at which the key would be inserted into the
array: the index of the first element greater than the key
4. or a.length if all elements in the array are less than the specified key.
PROGRAM:
class BinarySearch
{ int binarySearch(int arr[], int l, int r, int x)
{ if (r>=l)
{ int mid = l + (r - l)/2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, l, mid-1, x);
return binarySearch(arr, mid+1, r, x);
}
return -1;
}
public static void main(String args[])
{ BinarySearch ob = new BinarySearch();
int arr[] = {2,3,4,10,40};
int n = arr.length;
int x = 10;
5
CS3381-OOP LAB GIT
RESULT:
Thus the implementation of recursive Binary Search using java program is
executed successfully.
6
CS3381-OOP LAB GIT
EXNO:2(c)
DATE:
THE SELECTION SORT ALGORITHM
AIM:
Java program for the implementation of the selection sort algorithm.
PROCEDURE:
Selection Sort (A, N)
Step 1: Repeat Steps 2 and 3 for K = 1 to N-1
Step 2: Call routine smallest(A, K, N, POS)
Step 3:Swap A[K] with A [POS]
[End of loop]
Step 4: EXIT
Routine smallest (A, K, N, POS)
Step 1: [initialize] set smallestItem = A[K]
Step 2: [initialize] set POS = K
Step 3:
for J = K+1 to N -1, repeat
if smallestItem > A [J]
set smallestItem = A [J]
set POS = J
[if end]
[End of loop]
Step 4: return POS
PROGRAM:
public class SelectionSortExample {
public static void selectionSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++){
if (arr[j] < arr[index]){
index = j;
7
CS3381-OOP LAB GIT
} }
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
} }
public static void main(String a[]){
int[] arr1 = {9,14,3,2,43,11,58,22};
System.out.println("Before Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
}
System.out.println();
selectionSort(arr1);
System.out.println("After Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
} } }
OUTPUT:
RESULT:
Thus the implementation of the selection sort using java program is executed
successfully.
8
CS3381-OOP LAB GIT
EXNO:2(d)
DATE:
INSERTION SORT ALGORITHM
AIM:
Java program for the implementation of the Insertion sort algorithm.
PROCEDURE:
To sort an array of size N in ascending order:
Iterate from arr[1] to arr[N] over the array.
Compare the current element (key) to its predecessor.
If the key element is smaller than its predecessor, compare it to the elements before.
Move the greater elements one position up to make space for the swapped element.
PROGRAM:
public class InsertionSortExample {
public static void insertionSort(int array[]) {
int n = array.length;
for (int j = 1; j < n; j++) {
int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) ) {
array [i+1] = array [i];
i--;
} array[i+1] = key;
} }
public static void main(String a[]){
int[] arr1 = {9,14,3,2,43,11,58,22};
System.out.println("Before Insertion Sort");
for(int i:arr1){
System.out.print(i+" ");
}
System.out.println();
9
CS3381-OOP LAB GIT
RESULT:
Thus the implementation of the insertion sort using java program is executed
successfully.
10
CS3381-OOP LAB GIT
EXNO:3(a)
DATE:
THE STACK DATA STRUCTURE
AIM:
Java program for the implementation of the stack data structure.
PROCEDURE:
Used the stack class to implement the stack in Java. Here,
animals.push() - insert elements to top of the stack
animals.pop() - remove element from the top of the stack
marks.push() - insert elements to top of the stack
marks.pop() - remove element from the top of the stack
PROGRAM:
import java.util.Stack;
class Stack_datastructure {
public static void main(String[] args) {
Stack<Integer> marks = new Stack<>();
Stack<String> animals= new Stack<>();
animals.push("Dog");
animals.push("Horse");
animals.push("Cat");
System.out.println("Stack: " + animals);
animals.pop();
System.out.println("Stack after pop: " + animals);
marks.push(79);
marks.push(90);
marks.push(57);
System.out.println("Stack: " + marks );
marks.pop();
System.out.println("Stack after pop: " + marks );}}
11
CS3381-OOP LAB GIT
OUTPUT:
RESULT:
Thus the implementation of the Stack data structure using java program is executed
successfully
12
CS3381-OOP LAB GIT
EXNO:3(B)
DATE:
THE QUEUE DATA STRUCTURE
AIM:
Java program for the implementation of the queue data structure.
PROCEDURE:
1. import java.util.queue; Or import java.util.*;
2. Once this is imported, we can create a queue as shown below:
Queue<String> str_queue = new LinkedList<> ();
3. Now that the queue object is created, we can initialize the queue object by providing
the values to it through the add method as shown below.
str_queue.add(“one”);
str_queue.add(“two”);
str_queue.add(“three”);
PROGRAM:
import java.util.*;
public class queue_datastructure {
public static void main(String[] args) {
Queue<Integer> q1 = new LinkedList<Integer>();
q1.add(10);
q1.add(20);
q1.add(30);
q1.add(40);
q1.add(50);
System.out.println("Elements in Queue:"+q1);
System.out.println("Element removed from the queue: "+q1.remove());
System.out.println("Head of the queue: "+q1.element());
System.out.println("Poll():Returned Head of the queue: "+q1.poll());
System.out.println("peek():Head of the queue: "+q1.peek());
System.out.println("Final Queue:"+q1);
}
}
13
CS3381-OOP LAB GIT
OUTPUT:
RESULT:
Thus the implementation of the Queue data structure using java program is executed
successfully.
14
CS3381-OOP LAB GIT
EXNO:4
DATE:
IMPLEMENTATION OF INHERITENCE
AIM:
To develop a java application to generate pay slip for different category of employees using
the concept of inheritance.
Procedure:
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();
System.out.println("Enter employee id ");
15
CS3381-OOP LAB GIT
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("************************************************");
System.out.println("Basic Pay:Rs"+bp);
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);
16
CS3381-OOP LAB GIT
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);
}}
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);
17
CS3381-OOP LAB GIT
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()
{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);
18
CS3381-OOP LAB GIT
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 ");
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();
19
CS3381-OOP LAB GIT
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();
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);
}}
20
CS3381-OOP LAB GIT
OUTPUT:
RESULT:
Thus, the implementation of inheritance using java program is executed successfully.
21
CS3381-OOP LAB GIT
EXNO:5
DATE:
IMPLEMENTATION OF ABSTRACT CLASS
AIM:
To develop a java application to calculate Area for different shapes using the concept of
abstract class.
Question:Write a Java program to create an abstract class named Shape that contains two
integers and an empty method named print Area (). Provide three classes named Rectangle,
Triangle, and Circle such that each one of the classes extends the class Shape. Each one of
the classes contains only the method print Area () that prints the area of the given shape
PROCEDURE:
Create a abstract class Shape.
Include variables length,breadth,radius and abstract method printArea()
Create class called Rectangle ,extend class Shape and implement the abstract
method printArea() and calculate the area of rectangle.
Create class called Triangle,extend class Shape and implement the abstract
method printArea() and calculate the area of triangle.
Create class called Circle ,extend class Shape and implement the abstract method
printArea() and calculate the area of circle .
PROGRAM:
import java.util.*;
abstract class Shape {
int length, breadth, radius;
Scanner input = new Scanner(System.in);
abstract void printArea();
}
class Rectangle extends Shape {
void printArea() {
System.out.println("*** Finding the Area of Rectangle ***");
System.out.print("Enter length and breadth: ");
length = input.nextInt();
breadth = input.nextInt();
System.out.println("The area of Rectangle is: " + length * breadth);}}
class Triangle extends Shape
{ void printArea()
22
CS3381-OOP LAB GIT
23
CS3381-OOP LAB GIT
OUTPUT:
RESULT:
Thus, the implementation of abstract class using java program is executed
successfully.
24
CS3381-OOP LAB GIT
EXNO:6
DATE:
IMPLEMENTATION OF INTERFACE
AIM:
To develop a java application to calculate Area for different shapes using the concept of
interface.
Question:Write a Java program to create an interface named Shape that contains two integers
and an empty method named print Area (). Provide three classes named Rectangle, Triangle,
and Circle such that each one of the classes implements the class Shape. Each one of the
classes contains only the method print Area () that prints the area of the given shape
STEP 1:Create a interface and save it as Shape_interface.java. Just save the program ,do not
compile the file.
PROGRAM:
interface Shape_interface {
public void printArea();
}
STEP 2:Create another java file named Demo_interface.java and compile the java file
PROGRAM:
import java.util.*;
class getDetails
{int length, breadth, radius;
Scanner input = new Scanner(System.in);
}
class Rectangle extends getDetails implements Shape_interface{
public void printArea() {
System.out.println("*** Finding the Area of Rectangle ***");
System.out.print("Enter length and breadth: ");
length = input.nextInt();
breadth = input.nextInt();
System.out.println("The area of Rectangle is: " + length * breadth);
}}
class Triangle extends getDetails implements Shape_interface
{ public void printArea()
25
CS3381-OOP LAB GIT
26
CS3381-OOP LAB GIT
OUTPUT:
RESULT:
Thus, the implementation of interface using java program is executed successfully.
27
CS3381-OOP LAB GIT
QUESTION:
Write a Java program to implement user defined exception handling to throw an exception by
getting a value from the user which is beyond the specified range.
ALGORITHM
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);System.out.print("Enter Amount:");int a=s.nextInt();
try
{if(a<0)
{throw new NegativeAmtException("Invalid Amount");
28
CS3381-OOP LAB GIT
}
System.out.println("Amount Deposited");
}
catch(NegativeAmtException e)
{
System.out.println(e);
}}}
OUTPUT
29
CS3381-OOP LAB GIT
B)PROGRAM
class MyException
extends Exception{
String str1;
MyException(String str2)
{
str1=str2;
}
public String toString()
{return ("MyException Occurred: "+str1) ;
}}
class example
{public static void main(String args[])
{
try
{
30
CS3381-OOP LAB GIT
OUTPUT
RESULT
Thus a java program to implement user defined exception handling has been
implemented andexecuted successfully.
31
CS3381-OOP LAB GIT
EXNO:8
DATE:
PROGRAM TO IMPLEMENT MULTITHREADING
AIM
To write a java program that implements a multi-threaded application.
QUESTION:
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 displaysthe 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);
}
}
32
CS3381-OOP LAB GIT
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
33
CS3381-OOP LAB GIT
Thread(new
odd(num));t2.start();
}
Thread.sleep(1000);
System.out.println(" -------------------------------------");
}
}
34
CS3381-OOP LAB GIT
OUTPUT
RESULT
Thus a java program for multi-threaded application has been implemented and executed
Successfully
35
CS3381-OOP LAB GIT
EXNO:9
DATE:
QUESTION:
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.
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 ");
filename=s.nextLine();
36
CS3381-OOP LAB GIT
OUTPUT
37
CS3381-OOP LAB GIT
RESULT
Thus, a java program to display file information has been implemented and executed
successfully.
38
CS3381-OOP LAB GIT
AIM
To write a java program to find the maximum value from the given type of elements using a
generic function.
QUESTION:
Write a java program to find the maximum value from the given type of elements using a
generic function
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
PROGRAM
class MyClass<T extends Comparable<T>>
{
T[] vals;
MyClass(T[] o)
{
vals = o;
}
public T min()
{
T v = vals[0];
39
CS3381-OOP LAB GIT
public T max()
{
T v = vals[0];
for(int i=1; i < vals.length;i++) 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};
40
CS3381-OOP LAB GIT
OUTPUT
RESULT
Thus, a java program to find the maximum value from the given type
of elements has been implemented using generics and executed
successfully.
41
CS3381-OOP LAB GIT
EXNO:11
DATE:
PROGRAM TO DESIGN A CALCULATOR USING
EVENT DRIVEN PROGRAMMING
QUESTION:
Decimal manipulations
Scientific manipulation
AIM
ALGORITHM
/*********************************************
Save this file as MyCalculator.java
to compile it use
javac MyCalculator.java
to use the calculator do this
java MyCalculator
**********************************************/
import java.awt.*;
import java.awt.event.*;
/*********************************************/
42
CS3381-OOP LAB GIT
String digitButtonText[] = {"7", "8", "9", "4", "5", "6", "1", "2", "3",
"0", "+/-", "." };
String operatorButtonText[] = {"/", "sqrt", "*", "%", "-", "1/X", "+",
"=" };
String memoryButtonText[] = {"MC", "MR", "MS", "M+" };
String specialButtonText[] = {"Backspc", "C", "CE" };
MyDigitButton digitButton[]=new
MyDigitButton[digitButtonText.length];
MyOperatorButton operatorButton[]=new
MyOperatorButton[operatorButtonText.length];
MyMemoryButton memoryButton[]=new
MyMemoryButton[memoryButtonText.length];
MySpecialButton specialButton[]=new
MySpecialButton[specialButtonText.length];
memLabel.setBounds(TOPX, TOPY+HEIGHT+
V_SPACE,WIDTH, HEIGHT);
add(memLabel);
43
CS3381-OOP LAB GIT
memoryButton[i]=new
MyMemoryButton(tempX,y,WIDTH,HEIGHT,memoryButtonText[i]
, this);
memoryButton[i].setForeground(Color.RED);
y+=HEIGHT+V_SPACE;
}
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent ev)
{System.exit(0);}
44
CS3381-OOP LAB GIT
});
setLayout(null);
setSize(FRAME_WIDTH,FRAME_HEIGHT);
setVisible(true);
}
//////////////////////////////////
static String getFormattedText(double temp)
{
String resText=""+temp;
if(resText.lastIndexOf(".0")>0)
resText=resText.substring(0,resText.length()-2);
return resText;
}
////////////////////////////////////////
public static void main(String []args)
{
new MyCalculator("Calculator - JavaTpoint");
}
}
/*******************************************/
//////////////////////////////////////////
MyDigitButton(int x,int y, int width,int height,String cap,
MyCalculator clc)
{
super(cap);
setBounds(x,y,width,height);
this.cl=clc;
this.cl.add(this);
addActionListener(this);
}
////////////////////////////////////////////////
static boolean isInString(String s, char ch)
{
for(int i=0; i<s.length();i++) if(s.charAt(i)==ch) return true;
return false;
}
/////////////////////////////////////////////////
public void actionPerformed(ActionEvent ev)
{
String tempText=((MyDigitButton)ev.getSource()).getLabel();
if(tempText.equals("."))
{
45
CS3381-OOP LAB GIT
if(cl.setClear)
{cl.displayLabel.setText("0.");cl.setClear=false;}
else if(!isInString(cl.displayLabel.getText(),'.'))
cl.displayLabel.setText(cl.displayLabel.getText()+".");
return;
}
int index=0;
try{
index=Integer.parseInt(tempText);
}catch(NumberFormatException e){return;}
if(cl.setClear)
{cl.displayLabel.setText(""+index);cl.setClear=false;}
else
cl.displayLabel.setText(cl.displayLabel.getText()+index);
}//actionPerformed
}//class defination
/********************************************/
cl.setClear=true;
double temp=Double.parseDouble(cl.displayLabel.getText());
if(opText.equals("1/x"))
{
try
{double tempd=1/(double)temp;
cl.displayLabel.setText(MyCalculator.getFormattedText(tempd));}
46
CS3381-OOP LAB GIT
catch(ArithmeticException excp)
{cl.displayLabel.setText("Divide by 0.");}
return;
}
if(opText.equals("sqrt"))
{
try
{double tempd=Math.sqrt(temp);
cl.displayLabel.setText(MyCalculator.getFormattedText(tempd));}
catch(ArithmeticException excp)
{cl.displayLabel.setText("Divide by 0.");}
return;
}
if(!opText.equals("="))
{
cl.number=temp;
cl.op=opText.charAt(0);
return;
}
// process = button pressed
switch(cl.op)
{
case '+':
temp+=cl.number;break;
case '-':
temp=cl.number-temp;break;
case '*':
temp*=cl.number;break;
case '%':
try{temp=cl.number%temp;}
catch(ArithmeticException excp)
{cl.displayLabel.setText("Divide by 0."); return;}
break;
case '/':
try{temp=cl.number/temp;}
catch(ArithmeticException excp)
{cl.displayLabel.setText("Divide by 0."); return;}
break;
}//switch
cl.displayLabel.setText(MyCalculator.getFormattedText(temp));
//cl.number=temp;
}//actionPerformed
}//class
/****************************************/
47
CS3381-OOP LAB GIT
MyCalculator cl;
/////////////////////////////////
MyMemoryButton(int x,int y, int width,int height,String cap,
MyCalculator clc)
{
super(cap);
setBounds(x,y,width,height);
this.cl=clc;
this.cl.add(this);
addActionListener(this);
}
////////////////////////////////////////////////
public void actionPerformed(ActionEvent ev)
{
char
memop=((MyMemoryButton)ev.getSource()).getLabel().charAt(1);
cl.setClear=true;
double temp=Double.parseDouble(cl.displayLabel.getText());
switch(memop)
{
case 'C':
cl.memLabel.setText(" ");cl.memValue=0.0;break;
case 'R':
cl.displayLabel.setText(MyCalculator.getFormattedText(cl.memValu
e));break;
case 'S':
cl.memValue=0.0;
case '+':
cl.memValue+=Double.parseDouble(cl.displayLabel.getText());
if(cl.displayLabel.getText().equals("0") ||
cl.displayLabel.getText().equals("0.0") )
cl.memLabel.setText(" ");
else
cl.memLabel.setText("M");
break;
}//switch
}//actionPerformed
}//class
/*****************************************/
48
CS3381-OOP LAB GIT
MyCalculator clc)
{
super(cap);
setBounds(x,y,width,height);
this.cl=clc;
this.cl.add(this);
addActionListener(this);
}
//////////////////////
static String backSpace(String s)
{
String Res="";
for(int i=0; i<s.length()-1; i++) Res+=s.charAt(i);
return Res;
}
//////////////////////////////////////////////////////////
public void actionPerformed(ActionEvent ev)
{
String opText=((MySpecialButton)ev.getSource()).getLabel();
//check for backspace button
if(opText.equals("Backspc"))
{
String tempText=backSpace(cl.displayLabel.getText());
if(tempText.equals(""))
cl.displayLabel.setText("0");
else
cl.displayLabel.setText(tempText);
return;
}
//check for "C" button i.e. Reset
if(opText.equals("C"))
{
cl.number=0.0; cl.op=' '; cl.memValue=0.0;
cl.memLabel.setText(" ");
}
}//class
49
CS3381-OOP LAB GIT
OUTPUT
RESULT
Thus, the program to design a calculator using event driven
programming was executed successfully.
50