Lab Manual-Oops FINAL
Lab Manual-Oops FINAL
A) Sequential Search
Aim:
To Develop a Java application to solve problems by using sequential search.
Procedure:
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:
import java.util.*;
class sequential
{
// Function for linear search
public static int search(int arr[], int x)
{
int n = arr.length;
// Traverse array arr[]
for (int i = 0; i < n; i++)
{
// If element found then
// return that index
if (arr[i] == x)
return i;
}
return -1;
}
// Driver Code
1
public static void main(String args[])
{
// Given arr[]
int arr[] = { 2, 3, 4, 10, 40 };
// Element to search
int x = 10;
// Function Call
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);
}
}
Output:
Result
Thus the Java application to solve problems by using sequential search was implemented and
Verified successfully.
2
b)Binary Search
Aim:
Procedure:
Program:
import java.util.*;
class Main
{
public static void main(String args[])
{
int numArray[] = {5,10,15,20,25,30,35};
System.out.println("The input array: " + Arrays.toString(numArray));
//key to be searched
int key = 20;
System.out.println("\nKey to be searched=" + key);
//set first to first index
int first = 0;
//set last to last elements in array
int last=numArray.length-1;
//calculate mid of the array
int mid = (first + last)/2;
3
//while first and last do not overlap
while( first <= last )
{
//if the mid < key, then key to be searched is in the first half of array
if ( numArray[mid] < key ){
first = mid + 1;
}
else if ( numArray[mid] == key )
{
//if key = element at mid, then print the location
System.out.println("Element is found at index: " + mid);
break;
}
else
{
//the key is to be searched in the second half of the array
last = mid - 1;
}
mid = (first + last)/2;
}
//if first and last overlap, then key is not present in the array
if ( first > last )
{
System.out.println("Element is not found!");
}
}
}
4
Output:
Result
Thus the Java application to solve problems by using binary search was implemented and
Verified successfully.
5
B) SELECTION SORT
Aim:
Procedure:
1. Finding the minimum value in the unsorted array and move it to the first position.
2. Now increase the pointer value by 1.
3. Again start searching for next minimal value in array (except in previous one)
4. If found minimal swap the value to second position element
5. Else leave it move pointer next
6. Sort the remaining values of data set (excluding the previous value).
Program:
public class SelectionSortEx
{
public static void main(String a[])
{
//Numbers which are to be sorted
int n[] = {55,33,22,88, 99,44,11, 77,66 };
//Displays the numbers before sorting
System.out.print("Before sorting, numbers are ");
for (int i = 0; i < n.length; i++) {
System.out.print(n[i] + " ");
}
System.out.println();
//Sorting in ascending order using bubble sort
initializeselectionSort(n);
//Displaying the numbers after sorting
System.out.print("After sorting, numbers are ");
for (int i = 0; i < n.length; i++) {
6
System.out.print(n[i] + " ");
}
}
//This method sorts the input array in descending order
public static void initializeselectionSort(int n[])
{
int i, j, first, temp;
for (i = n.length - 1; i > 0; i--) {
first = 0; //initialize to subscript of first element
for (j = 1; j <= i; j++) //locate smallest element between 1 and i.
{
if (n[j] < n[first])
first = j;
}
temp = n[first]; //swap the smallest found in position i.
n[first] = n[i];
n[i] = temp;
}
}
}
Output:
Result
Thus the Java application to solve problems by using selection sort was implemented and
Verified successfully.
7
C) INSERTION SORT
Aim:
Procedure:
1. Start inserting the values in array.
2. Assign the first value to first index.
3. For next value compare it with previous values.
4. If it is small from previous swap it from previous.
5. Else assign that value to next index.
6. Do that for all remaining values.
Program:
public class InsertionSortEx
{
public static void main(String a[])
{
//Numbers which are to be sorted
int n[] = {124, 23, 43, 12, 177, 25, 2, 1,67};
//Displays the numbers before sorting
System.out.print("Before sorting, numbers are ");
for (int i = 0; i < n.length; i++)
{
System.out.print(n[i] + " ");
}
System.out.println();
//Sorting in ascending order using bubble sort
initializeInsertionSort(n);
//Displaying the numbers after sorting
System.out.print("After sorting, numbers are ");
for (int i = 0; i < n.length; i++)
{
System.out.print(n[i] + " ");
}
8
}
//This method sorts the input array in asecnding order
public static void initializeInsertionSort(int n[])
{
for (int i = 1; i < n.length; i++)
{
int j = i;
int B = n[i];
while ((j > 0) && (n[j - 1] > B))
{
n[j] = n[j - 1];
j--;
}
n[j] = B;
}
}
}
Output:
Result
Thus the Java application to solve problems by using insertion sort was implemented and
Verified successfully.
9
Expt. No: 2
Date: STACK & QUEUE IMPLEMENTATION
A) STACK IMPLEMENTATION
Aim:
To Develop a Java application to implement stack using classes and objects.
Algorithm:
1. push inserts an item at the top of the stack (i.e., above its current top element).
2. pop removes the object at the top of the stack and returns that object from the function.
5. peek returns the object at the top of the stack without removing it from the stack
Program:
class Stack
{
private int arr[];
private int top;
private int capacity;
// Constructor to initialize the stack
Stack(int size)
{
arr = new int[size];
capacity = size;
top = -1;
}
// Utility function to add an element `x` to the stack
public void push(int x)
{
if (isFull())
10
{
System.out.println("Overflow\nProgram Terminated\n");
System.exit(-1);
}
System.out.println("Inserting " + x);
arr[++top] = x;
}
// Utility function to pop a top element from the stack
public int pop()
{
// check for stack underflow
if (isEmpty())
{
System.out.println("Underflow\nProgram Terminated");
System.exit(-1);
}
System.out.println("Removing " + peek());
// decrease stack size by 1 and (optionally) return the popped element
return arr[top--];
}
// Utility function to return the top element of the stack
public int peek()
{
if (!isEmpty())
{
return arr[top];
}
else
{
System.exit(-1);
}
return -1;
}
// Utility function to return the size of the stack
11
public int size()
{
return top + 1;
}
// Utility function to check if the stack is empty or not
public boolean isEmpty()
{
return top == -1; // or return size() == 0;
}
// Utility function to check if the stack is full or not
public boolean isFull()
{
return top == capacity - 1; // or return size() == capacity;
}
}
class Main
{
public static void main (String[] args)
{
Stack stack = new Stack(3);
stack.push(1); // inserting 1 in the stack
stack.push(2); // inserting 2 in the stack
stack.pop(); // removing the top element (2)
stack.pop(); // removing the top element (1)
stack.push(3); // inserting 3 in the stack
System.out.println("The top element is " + stack.peek());
System.out.println("The stack size is " + stack.size());
stack.pop(); // removing the top element (3)
// check if the stack is empty
if (stack.isEmpty()) {
System.out.println("The stack is empty");
}
12
else
{
System.out.println("The stack is not empty");
}
}
}
Output:
Result
Thus the Java application of Stack data structure has been implemented and Verified successfully.
13
B) QUEUE IMPLEMENTATION
Aim:
To Develop a Java application to implement queue using classes and objects.
Algorithm:
1. Enqueue: Inserts an item at the rear of the queue.
2. Dequeue: Removes the object from the front of the queue and returns it, thereby
decrementing queue size by one.
3. Peek: Returns the object at the front of the queue without removing it.
4. IsEmpty: Tests if the queue is empty or not.
5. Size: Returns the total number of elements present in the queue.
Program:
class Queue
private int front; // front points to the front element in the queue
private int rear; // rear points to the last element in the queue
Queue(int size)
capacity = size;
front = 0;
rear = -1;
14
count = 0;
if (isEmpty())
System.out.println("Underflow\nProgram Terminated");
System.exit(-1);
int x = arr[front];
count--;
return x;
if (isFull())
System.out.println("Overflow\nProgram Terminated");
System.exit(-1);
15
System.out.println("Inserting " + item);
arr[rear] = item;
count++;
if (isEmpty())
System.out.println("Underflow\nProgram Terminated");
System.exit(-1);
return arr[front];
return count;
16
class Main
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
q.dequeue();
q.dequeue();
q.dequeue();
if (q.isEmpty())
else
} } }
17
Output:
Result
Thus the Java application of Queue data structure has been implemented and Verified
successfully.
18
Expt. No: 3 EMPLOYEE SALARY CALCULATION USING INHERITANCE
Date: CONCEPTS
Aim:
To develop a java application with Employee class with Emp_name, Emp_id,
Address, Mail_id, Mobile_no as members. Inherit the classes, Programmer, Assistant
Professor, Associate Professor and Professor from employee class and Generate pay slipsfor
the employees with their gross and net salary with respected to given statementsbelow.
Procedure:
1. Create a base class Employee, necessary members and methods to read / display the
employeeinformation.
2. Create subclasses Programmer, AssistantProfessor, AssociateProfessor and Professor
derived from Employee class and overload and override methods
like(getEmployeeDetails(basicPay) and display(). in addition cal() method which is
used to salary calculation based on employee designation with respected to problem
statements.
Program
import java.util.Scanner;
public class EmployeeSalaryCalc
{
public static void main(Stringargs[])
{
Scanner obj=newScanner(System.in);
Programmer p=newProgrammer();
System.out.println("Enter the basic pay of Programmer");
p.getEmployeeDetails(obj.nextDouble());
p.cal();
AssistantProfessor ap=new AssistantProfessor();
System.out.println("Enter the basic pay of Assistant Professor");
ap.getEmployeeDetails(obj.nextDouble());
ap.cal();
AssociateProfessor asp=new AssociateProfessor();
System.out.println("Enter the basic pay of Associate Professor");
19
asp.getEmployeeDetails(obj.nextDouble());
asp.cal();
Professor prof=new Professor();
System.out.println("Enter the basic pay ofProfessor");
prof.getEmployeeDetails(obj.nextDouble());
prof.cal();
}
}
class Employee{
String employeeName;
int employeeID;
Stringaddress;
StringmailID;
long mobileNumber;
double da,hra,pf,sc,ns,gs;
Scanner obj=new Scanner(System.in);
void getEmployeeDetails()
{
System.out.println("Enter the Employee Name:");
employeeName=obj.nextLine();
System.out.println("Enter the Employee Address:");
address=obj.nextLine();
System.out.println("Enter the Employee Mail ID:");
mailID=obj.nextLine();
System.out.println("Enter the Employee ID:");
employeeID=obj.nextInt();
System.out.println("Enter the Employee Mobile Number:");
mobileNumber=obj.nextLong();
}
void display()
20
System.out.println("EmployeeName :"+employeeName);
System.out.println("EmployeeID :"+employeeID);
System.out.println("EmployeeAddress :"+address);
System.out.println("EmployeeMail ID :"+mailID);
System.out.println("Employee MobileNumber:"+mobileNumber);
}
}
class Programmer extends Employee
{
double basicPay;
public double getBasicPay()
{
return basicPay;
}
public void setBasicPay(double basicPay)
{
this.basicPay = basicPay;
}
void getEmployeeDetails(double bp)
{
super.getEmployeeDetails();
setBasicPay(bp);
}
void cal(){ da=getBasicPay()*97/100.0;
hra=getBasicPay()*10/100.0;
pf=getBasicPay()*12/100.0;
sc=getBasicPay()*1/100.0;
gs=getBasicPay()+da+hra+pf+sc;
ns=gs-pf-sc;
display();
}
void display()
{
21
super.display();
System.out.println("Employee Gross Salary:"+gs);
System.out.println("Employee Net Salary:"+ns);
}
}
class AssistantProfessor extendsEmployee
{
double basicPay;
public double
getBasicPay()
{
return basicPay;
}
public void setBasicPay(double basicPay)
{
this.basicPay = basicPay;
}
super.getEmployeeDetails();
setBasicPay(bp);
}
void cal(){
da=getBasicPay()*110/100.0;
hra=getBasicPay()*20/100.0;
pf=getBasicPay()*12/100.0;
sc=getBasicPay()*5/100.0;
gs=getBasicPay()+da+hra+pf+
sc; ns=gs-pf-sc;
display();
}
22
void display()
{
super.display();
System.out.println("Employee Gross Salary:"+gs);
System.out.println("Employee Net Salary:"+ns);
}
}
class AssociateProfessor extends Employee
{
double basicPay;
public double
getBasicPay()
{
return basicPay;
}
public void setBasicPay(double basicPay)
{
this.basicPay = basicPay;
}
void getEmployeeDetails(double bp)
{
super.getEmployeeDetails();
setBasicPay(bp);
}
void cal()
{
da=getBasicPay()*130/100.0;
hra=getBasicPay()*30/100.0;
pf=getBasicPay()*12/100.0;
sc=getBasicPay()*10/100.0;
gs=getBasicPay()+da+hra+pf+
sc; ns=gs-pf-sc;
display();
}
23
void display()
{
super.display();
System.out.println("Employee Gross Salary:"+gs);
System.out.println("Employee Net Salary:"+ns);
}
}
double basicPay;
public double
getBasicPay()
{
return basicPay;
}
public void setBasicPay(double basicPay)
{
this.basicPay = basicPay;
}
void getEmployeeDetails(double bp)
{
super.getEmployeeDetails();
setBasicPay(bp);
}
void cal()
{
da=getBasicPay()*140/100.0;
hra=getBasicPay()*40/100.0;
pf=getBasicPay()*12/100.0;
sc=getBasicPay()*15/100.0;
gs=getBasicPay()+da+hra+pf+sc;
ns=gs-pf-sc;
display();
24
}
void display(){
super.display();
System.out.println("Employee Gross Salary:"+gs);
System.out.println("Employee Net Salary:"+ns);
}
}
Output:
Enter the basic pay of Programmer
15000
Enter the Employee Name:
ram
Enter the Employee Address:
56 Ganga Street
Enter the Employee Mail
ID: [email protected]
Enter the Employee ID:
101
Enter the Employee Mobile
Number: 9994117284
EmployeeName :ram
EmployeeID 101
25
Enter the basic pay of Assistant Professor
20000
Enter the Employee Name:
vinu
Enter the Employee Address:
75 public office road
Enter the Employee Mail
ID: [email protected]
Enter the Employee ID:
201
Enter the Employee Mobile
Number: 9842321130
EmployeeName :vinu
Employee ID 201
EmployeeAddress :75 public office road
EmployeeMail ID :[email protected]
Employee Mobile Number:9842321130
Employee Gross Salary:49400.0
Employee Net Salary:46000.0
26
EmployeeMail ID :[email protected]
Employee Mobile Number:9578621131
Employee Gross Salary:84600.0
Employee Net Salary:78000.0
Result
Thus the java program to calculate the employee salary using inheritance concepts was
implemented and verified successfully.
27
Expt. No: 4
Date: ABSTRACT CLASS
Aim:
To 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,
TriangleandCirclesuchthateachoneoftheclassesextendstheclassShape.Eachoneofthe classes
contains only the method print Area () that prints the area of the givenshape.
Procedure:
1. Create a class Shape with necessary members and abstract methodprintArea()
2. Create sub classes Rectangle and Triangle derived from Shape andoverride
theprintArea()
Program
import java.util.*;
abstract class shape
{
int x,y;
abstract void area(double x,double y);
}
class Rectangle extends shape
{
void area(double x,double y)
{
System.out.println("Area of rectangle is :"+(x*y));
}
}
class Circle extends shape
{
void area(double x,double y)
{
28
System.out.println("Area of circle is :"+(3.14*x*x));
}
}
class Triangle extends shape
{
void area(double x,double y)
{
System.out.println("Area of triangle is :"+(0.5*x*y));
}
}
public class AbstactDDemo
{
public static void main(String[] args)
{
Rectangle r=new Rectangle();
r.area(2,5);
Circle c=new Circle();
c.area(5,5);
Triangle t=new Triangle();
t.area(2,5);
}
}
Output:
Result:
Thus the java program to demonstrate Abstract Class was implemented and verified
successfully.
29
Expt. No: 5
Date: INTERFACE
Aim:
To write a Java Program to create an interface named Shape that contains two methods
input() and area(). Provide two classes named Rectangle,
andCirclesuchthateachoneoftheclassesextendstheclassShape.Eachoneofthe classes
contains the necessary methods that prints the area of the givenshape.
Procedure:
1. Create a class Demo with necessary members and an interface Shape.
2. Create sub classes Rectangle and Circle derived from Shape andoverride the
methods input() and area().
Program:
interface Shape
void input();
void area();
int r = 0;
double pi = 3.14, ar = 0;
@Override
r = 5;
30
@Override
ar = pi * r * r;
System.out.println("Area of circle:"+ar);
int l = 0, b = 0;
double ar;
super.input();
l = 6;
b = 4;
super.area();
ar = l * b;
System.out.println("Area of rectangle:"+ar);
31
public static void main(String[] args)
obj.input();
obj.area();
Output:
Result
Thus the java program to demonstrate interface was implemented and verifiedsuccessfully.
32
Expt. No: 6
Date: USER DEFINED EXCEPTION HANDLING
Aim:
Procedure:
Program:
package javaapplication12;
import java.util.Scanner;
class NegativeAmtException extends Exception
{
String msg;
NegativeAmtException(String msg)
{
this.msg=msg;
}
public String toString()
{
return msg;
}
}
33
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");
}
System.out.println("Amount Deposited");
}
catch(NegativeAmtException e)
{
System.out.println(e);
}
}
}
Output:
Result
Thus the java program to demonstrate user defined exception handling was implemented and
verified successfully.
34
Expt. No: 7
Date: MULTI THREADED APPLICATION
Aim:
To write a Java program to implement Multithreaded Application.
Procedure:
4. If the random number generated is even, create a second thread to compute the square of the
35
public OddNum(int a)
{
this.a = a;
}
public void run()
{
System.out.println("The Thread "+ a +" is ODD and Cube of " + a + " is: " + a * a * a);
}
}
class RandomNumGenerator extends Thread
{
public void run()
{
int n = 0;
Random rand = new Random();
try
{
for (int i = 0; i < 10; i++)
{
n = rand.nextInt(20);
System.out.println("Generated Number is " + n);
if (n % 2 == 0)
{
Thread thread1 = new Thread(new EvenNum(n));
thread1.start();
}
else
{ Thread thread2 = new Thread(new OddNum(n));
thread2.start();
}
Thread.sleep(1000);
System.out.println(" ");
}
}
36
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
public class MultiThreadRandOddEven
{
public static void main(String[] args)
{
RandomNumGenerator rand_num = new RandomNumGenerator();
rand_num.start();
}
}
Output:
Result
Thus, the java program to demonstrate multithreaded application was implemented and
verified successfully.
37
Expt. No: 8
Date: FILE OPERATIONS
Aim:
To write a Java program to implement File Operations.
Procedure:
1. Declare the package
2. Import the necessary file handling packages.
3. Create a new file using the class “File” in your local location.
4. Check if the file is created and print the name of it else print the error message.
5. Print the following file related messages if the file exists,
a. The name of the file.
b. The absolute path of the file.
c. Check if the file is writeable.
d. Check if the file is readable.
e. The size of the file in bytes.
6. Using the “FileWriter” class, open and write something in the file and close it.
7. Using the “Scanner class” open and read the file content, print it, and then close the file.
8. Perform all the file operations in try catch block to capture the exceptions.
9. Finally delete the file from the location and print the message.
Program:
package javaapplication4;
import java.io.IOException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.Scanner;
public class JavaApplication4
{
public static void main(String args[])
{
38
File f0 = new File("D:wordfile.txt");
try
{
if (f0.createNewFile())
{
System.out.println("File " + f0.getName() + " is created successfully.");
}
else
{
System.out.println("File is already exist in the directory.");
}
}
catch (IOException exception)
{
39
fwrite.close();
System.out.println("Content is successfully wrote to the file.");
}
catch(IOException e)
{
System.out.println("Unexpected error occurred");
e.printStackTrace();
}
try
{
File f1 = new File("D:wordfile.txt");
Scanner dataReader = new Scanner(f1);
while (dataReader.hasNextLine())
{
String fileData = dataReader.nextLine();
System.out.println(fileData);
}
dataReader.close();
}
catch (FileNotFoundException exception)
{
System.out.println("Unexcpected error occurred!");
exception.printStackTrace();
}
try
{
File f1 = new File("D:FileOperationExample.txt");
Scanner dataReader = new Scanner(f1);
while (dataReader.hasNextLine())
{
String fileData = dataReader.nextLine();
System.out.println(fileData);
}
40
dataReader.close();
}
catch (FileNotFoundException exception)
{
System.out.println("Unexcpected error occurred!");
exception.printStackTrace();
}
if (f0.delete())
{
System.out.println(f0.getName()+ " file is deleted successfully.");
}
else
{
System.out.println("Unexpected error found in deletion of the file.");
}
} }
Output:
Result
Thus the java program to demonstrate file operation was implemented and verified successfully.
41
Expt. No: 9
Date: GENERICS CLASSES
Aim:
To write a Java program to Demonstrate features of generic classes.
Procedure:
1. Declare the package
2. Import the necessary library packages
3. Create a new list using generic class ArrayList of type ‘string’.
4. Add few string data to the list.
5. Try adding an integer to this list and check if it throws compile time error. This will verify the compile
time safety feature of Generics.
6. Get the position 2 from the list without any cast. This will verify the type casting feature of the Generics.
Program:
package javaapplication6;
import java.util.*;
import java.util.Iterator;
public class JavaApplication6
{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("rahul");
list.add("jai");
list.add("cse");
list.add("AEC");
//list.add(32);//compile time error
String s=list.get(2);//type casting is not required
System.out.println("element is: "+s);
Iterator<String> itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
42
Output:
Result
Thus the java program to demonstrate features of generic classes was implemented and verified
successfully.
43
Expt. No: 10
Date: JAVAFX CONTROLS
A) LAYOUT
Aim:
To write a Java program to Demonstrate layout option JavaFx controls.
Procedure:
1. Create this class in JavaFx category.
2. Declare the package
3. Import the necessary javaFx packages.
4. Implement the Border GUI functions available in javafx.
5. Create a new border pane and set all the sides such as top, bottom, left, right and center attributes.
6. This creates a window with all the sides defined by the class.
Program:
package javafxapplication2;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class Label_Test extends Application
{
@Override
public void start(Stage primaryStage) throws Exception
{
BorderPane BPane = new BorderPane();
BPane.setTop(new Label("This will be at the top"));
BPane.setLeft(new Label("This will be at the left"));
BPane.setRight(new Label("This will be at the Right"));
BPane.setCenter(new Label("This will be at the Centre"));
BPane.setBottom(new Label("This will be at the bottom"));
44
Scene scene = new Scene(BPane,600,400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args)
{
launch(args);
}
}
Output:
Result
Thus the java program to demonstrate layout of JavaFX Control was implemented and verified
successfully.
45
B) MENU
Aim:
To write a Java program to Demonstrate Menu option JavaFx controls.
Procedure:
1. Create this class in JavaFx category.
2. Declare the package
3. Import the necessary javaFx packages.
4. Create a new border pane using javaFx.
5. Using ‘MenuBar’ class, create and define the meAnu options.
6. This creates a window with all the menu options defined by the class.
Program:
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class MenuExample extends Application
{
public static void main(String[] args)
{
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception
{
// TODO Auto-generated method stub
BorderPane root = new BorderPane();
Scene scene = new Scene(root,200,300);
MenuBar menubar = new MenuBar();
Menu FileMenu = new Menu("File");
MenuItem filemenu1=new MenuItem("new");
MenuItem filemenu2=new MenuItem("Save");
46
MenuItem filemenu3=new MenuItem("Exit");
Menu EditMenu=new Menu("Edit");
MenuItem EditMenu1=new MenuItem("Cut");
MenuItem EditMenu2=new MenuItem("Copy");
MenuItem EditMenu3=new MenuItem("Paste");
EditMenu.getItems().addAll(EditMenu1,EditMenu2,EditMenu3);
root.setTop(menubar);
FileMenu.getItems().addAll(filemenu1,filemenu2,filemenu3);
menubar.getMenus().addAll(FileMenu,EditMenu);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Output:
Result:
Thus the java program to demonstrate menu option of JavaFX Control was implemented and
verified successfully.
47
Expt. No:11
Date: MINI PROJECT
Aim:
To write a Java program to Demonstrate simple calculator application in java.
Procedure:
1. Create a class which extends the ‘Frame’ class.
2. Declare the variables needed.
3. Define all the button texts needed in the calculator.
4. Define the properties for the calculator appearance such background and front designs.
5. Write the logic for all arithmetic operations declared and return the output.
6. Get the output and display in the calculator.
Program:
package javaapplication11;
import java.awt.*;
import java.awt.event.*;
public class MyCalculator extends Frame
{
public boolean setClear=true;
double number, memValue;
char op;
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];
Label displayLabel=new Label("0",Label.RIGHT);
Label memLabel=new Label(" ",Label.RIGHT);
final int FRAME_WIDTH=325,FRAME_HEIGHT=325;
final int HEIGHT=30, WIDTH=30, H_SPACE=10,V_SPACE=10;
final int TOPX=30, TOPY=50;
48
MyCalculator(String frameText)
{
super(frameText);
int tempX=TOPX, y=TOPY;
displayLabel.setBounds(tempX,y,240,HEIGHT);
displayLabel.setBackground(Color.BLUE);
displayLabel.setForeground(Color.WHITE);
add(displayLabel);
memLabel.setBounds(TOPX, TOPY+HEIGHT+ V_SPACE,WIDTH, HEIGHT);
add(memLabel);
tempX=TOPX;
y=TOPY+2*(HEIGHT+V_SPACE);
for(int i=0; i<memoryButton.length; i++)
{
memoryButton[i]=new MyMemoryButton(tempX,y,WIDTH,HEIGHT,memoryButtonText[i], this);
memoryButton[i].setForeground(Color.RED);
y+=HEIGHT+V_SPACE;
}
tempX=TOPX+1*(WIDTH+H_SPACE); y=TOPY+1*(HEIGHT+V_SPACE);
for(int i=0;i<specialButton.length;i++)
{
specialButton[i]=new MySpecialButton(tempX,y,WIDTH*2,HEIGHT,specialButtonText[i], this);
specialButton[i].setForeground(Color.RED);
tempX=tempX+2*WIDTH+H_SPACE;
}
int digitX=TOPX+WIDTH+H_SPACE;
int digitY=TOPY+2*(HEIGHT+V_SPACE);
tempX=digitX; y=digitY;
for(int i=0;i<digitButton.length;i++)
{
digitButton[i]=new MyDigitButton(tempX,y,WIDTH,HEIGHT,digitButtonText[i], this);
digitButton[i].setForeground(Color.BLUE);
tempX+=WIDTH+H_SPACE;
if((i+1)%3==0){tempX=digitX; y+=HEIGHT+V_SPACE;}
49
CS 3381– Object Oriented Programming Laboratory Arasu Engineering College, Kumbakonam
}
int opsX=digitX+2*(WIDTH+H_SPACE)+H_SPACE;
int opsY=digitY;
tempX=opsX; y=opsY;
for(int i=0;i<operatorButton.length;i++)
{
tempX+=WIDTH+H_SPACE;
operatorButton[i]=new MyOperatorButton(tempX,y,WIDTH,HEIGHT,operatorButtonText[i], this);
operatorButton[i].setForeground(Color.RED);
if((i+1)%2==0){tempX=opsX; y+=HEIGHT+V_SPACE;}
}
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent ev)
{
System.exit(0);
}
});
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");
}
}
50
CS 3381– Object Oriented Programming Laboratory Arasu Engineering College, Kumbakonam
51
CS 3381– Object Oriented Programming Laboratory Arasu Engineering College, Kumbakonam
catch(NumberFormatException e)
{
return;
}
if (index==0 && cl.displayLabel.getText().equals("0")) return;
if(cl.setClear)
{
cl.displayLabel.setText(""+index);cl.setClear=false;
}
else
cl.displayLabel.setText(cl.displayLabel.getText()+index);
}
}
class MyOperatorButton extends Button implements ActionListener
{
MyCalculator cl;
MyOperatorButton(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)
{
String opText=((MyOperatorButton)ev.getSource()).getLabel();
cl.setClear=true;
double temp=Double.parseDouble(cl.displayLabel.getText());
if(opText.equals("1/x"))
{
try
{
52
CS 3381– Object Oriented Programming Laboratory Arasu Engineering College, Kumbakonam
double tempd=1/(double)temp;
cl.displayLabel.setText(MyCalculator.getFormattedText(tempd));
}
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;
}
switch(cl.op)
{
case '+':
temp+=cl.number;break;
case '-':
temp=cl.number-temp;break;
53
CS 3381– Object Oriented Programming Laboratory Arasu Engineering College, Kumbakonam
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));
}
}
class MyMemoryButton extends Button implements ActionListener
{
MyCalculator cl;
MyMemoryButton(int x,int y, int width,int height,String cap, MyCalculator clc)
{
54
CS 3381– Object Oriented Programming Laboratory Arasu Engineering College, Kumbakonam
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.memValue));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;
}
}
}
class MySpecialButton extends Button implements ActionListener
{
MyCalculator cl;
MySpecialButton(int x,int y, int width,int height,String cap, MyCalculator clc)
{
55
CS 3381– Object Oriented Programming Laboratory Arasu Engineering College, Kumbakonam
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();
if(opText.equals("Backspc"))
{
String tempText=backSpace(cl.displayLabel.getText());
if(tempText.equals(""))
cl.displayLabel.setText("0");
else
cl.displayLabel.setText(tempText);
return;
}
if(opText.equals("C"))
{
cl.number=0.0; cl.op=' '; cl.memValue=0.0;
cl.memLabel.setText(" ");
}
cl.displayLabel.setText("0");cl.setClear=true;
}
}
56
CS 3381– Object Oriented Programming Laboratory Arasu Engineering College, Kumbakonam
Output:
Result
Thus the java program to demonstrate simple calculator application was implemented and
verified successfully.
57