[go: up one dir, main page]

0% found this document useful (0 votes)
66 views109 pages

Oops Manualfinal

The document discusses implementing a stack data structure in Java using classes and objects. It provides the algorithm, sample program code and output to demonstrate pushing, popping, peeking and checking if the stack is empty.

Uploaded by

saranya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views109 pages

Oops Manualfinal

The document discusses implementing a stack data structure in Java using classes and objects. It provides the algorithm, sample program code and output to demonstrate pushing, popping, peeking and checking if the stack is empty.

Uploaded by

saranya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 109

EX.

NO:1(a) SEQUENTIAL SEARCH

DATE:

Aim:

To write a java program to solve problem by a sequential search.

Algorithm:

Step 1: Start the program .

Step 2: Get the input as integer array.

Step 3: Traverse the array.

Step 4: Match the key element with array element.

Step 5: If key element is found, return the index position of the array
element.

Step 6: If key element is not found, return -1.

Step 7: Display the output.

Step 8: Stop the program.

Program:

import java.util.Scanner;

class linearsearch

public static void main(String args[])

int c, n, search, array[];

Scanner in = new Scanner(System.in);

System.out.println("Enter number of elements");

n = in.nextInt();

1
array = new int[n];

System.out.println("Enter those " + n + " elements");

for (c = 0; c < n; c++)

array[c] = in.nextInt();

System.out.println("Enter value to find");

search = in.nextInt();

for (c = 0; c < n; c++)

if (array[c] == search) /* Searching element is present */

System.out.println(search + " is present at location " + (c + 1) + ".");

break;

if (c == n) /* Element to search isn't present */

System.out.println(search + " isn't present .");

2
Output:

Result:
Thus the above program was successfully executed and the output was
verified.

3
EX.NO:1(b) BINARY SEARCH

DATE:

Aim:

To write a java program to solve problems by using binary search.

Algorithm:

Step 1: Start the program.

Step 2: Traverse the array.

Step 3: Find the middle element of array using middle =initial_value


+

End_value/2.

Step 4: If middle > element,call() with end_value =middle-1.

Step 5: If middle < element,call() with start_value=middle+1.

Step 6: stop the program.

Program:

import java.util.Scanner;

class binary

public static void main(String args[]){

int c, first, last, middle, n, search, array[];

Scanner in = new Scanner(System.in);

System.out.println("Enter number of elements");

n = in.nextInt();

array = new int[n];

4
System.out.println("Enter " + n + " integers");

for (c = 0; c < n; c++)

array[c] = in.nextInt();

System.out.println("Enter value to find");

search = in.nextInt();

first = 0;

last = n - 1;

middle = (first + last)/2;

while( first <= last ){

if ( array[middle] < search )

first = middle + 1;

else if ( array[middle] == search )

System.out.println(search + " found at location " + (middle + 1) + ".");

break;

else

last = middle - 1;

middle = (first + last)/2;

if (first > last)

System.out.println(search + " isn't present in the list.\n");

5
Output:

Result:
Thus the above program was successfully executed and the output was
verified.

6
EX.NO:1(c) SELECTION SORT

DATE:

Aim:

To write a java program to solve problems using quadratic sorting


algorithms on selection sort.

Algorithm:

Step 1: Start the program.

Step 2: Traverse the array.

Step 3: Call smallest (arr,I,n,pos).

Step 4: Swap arr[i] with arr[pos].

Step 5: End of the loop.

Step 6: stop the program.

Program:

import java.util.Scanner;

public class selection

public static void main(String args[]) {

int size, i, j, temp;

int arr[] = new int[50];

Scanner scan = new Scanner(System.in);

System.out.print("Enter element Size : ");

size = scan.nextInt();

System.out.print("Enter " +size+ " Elements : ");

7
for(i=0; i<size; i++)

arr[i] = scan.nextInt();

System.out.print("Sorting element using Selection Sort Technique..\n");

for(i=0; i<size; i++)

for(j=i+1; j<size; j++)

if(arr[i] > arr[j])

temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

System.out.print("Now the elements after Sorting is :\n");

for(i=0; i<size; i++)

System.out.print(arr[i]+ " ");

8
Output:

Result:
Thus the above program was successfully executed and the output was
verified.

9
EX.NO:1(d) INSERTION SORT

DATE:

Aim:

To write a java program to solve problems using quadratic sorting


algorithms on insertion sort.

Algorithm:

Step 1: Start the program.

Step 2: Traverse the array.

Step 3: If the element is the 1st element and store it separately in a key.

Step 4: Now,compare the key with all elements in the sorted array.

Step 5: If the element in the sorted array is smaller than the current

element,then move to the next element.

Step 5.1: Else,Shift greater elements in the array towards the right.

Step 6: Insert the value.

Step 7: Stop the program.

Program:

import java.util.Scanner;

public class insert

public static void main(String[] args)

int n, i, j, element;

Scanner scan = new Scanner(System.in);

10
System.out.print("Enter the Size of elements: ");

n = scan.nextInt();

int[] arr = new int[n];

System.out.print("Enter " +n+ " Elements: ");

for(i=0; i<n; i++)

arr[i] = scan.nextInt();

for(i=1; i<n; i++)

element = arr[i];

for(j=(i-1); j>=0 && arr[j]>element; j--)

arr[j+1] = arr[j];

arr[j+1] = element;

System.out.println("\nThe new sorted element using insertion sort is: ");

for(i=0; i<n; i++)

System.out.print(arr[i]+ " ");

11
Output:

Result:
Thus the above program was successfully executed and the output was
verified.

12
EX.NO:2(a) STACK USING DATA STRUCTURE

DATE:

Aim:

To write a java program to develop stack using classes and object.

Algorithm:

Step 1: Start the program.

Step 2: Check if the stack is full.

Step 3: If the stack is full, produces an error and exit.

Step 4: If the stack is not full, increment top to point next empty space.

Step 5: Add data element to the stack location, where top is pointing.

Program:

import java.util.*;

class Stack

int[] a;

int top;

Stack()

a=new int[100];

top=-1;

void push(int x)

13
if(top==a.length-1)

System.out.println("overflow");

else

a[++top]=x;

int pop()

if(top==-1)

{System.out.println("underflow");

return -1;

else

return(a[top--]);

void display()

for(int i=0;i<=top;i++)

System.out.print(a[i]+" ");

System.out.println();

boolean isEmpty()

14
{

if(top==-1)

return true;

else

return false;

int peek()

if(top==-1)

return -1;

return (a[top]);

public class demo

public static void main(String args[])

Stack s=new Stack();

Scanner in= new Scanner(System.in);

Do

15
{

System.out.println("\n******** MENU *******");

System.out.println("\n1.PUSH");

System.out.println("\n2.POP");

System.out.println("\n3.PEEK");

System.out.println("\n4 IS EMPTY");

System.out.println("\n5.EXIT");

System.out.println("\n enter ur choice : ");

switch(in.nextInt())

case 1:

System.out.println("\n enter the value ");

s.push(in.nextInt());

break;

case 2:

System.out.println("\n popped element : "+


s.pop());

break;

case 3:

System.out.println("\n top element : "+


s.peek());

break;

case 4: System.out.println("\n is empty : "+


s.isEmpty());

16
break;

case 5: System.exit(0);

break;

default: System.out.println("\n Wrong Choice!");

break;

System.out.println("\n do u want to cont... ");

}while(in.nextInt()==1);

int n, i, j, element;

Scanner scan = new Scanner(System.in);

System.out.print("Enter stack size: ");

n = scan.nextInt();

int[] arr = new int[n];

System.out.print("Enter " +n+ " Elements: ");

for(i=0; i<n; i++)

arr[i] = scan.nextInt();

for(i=1; i<n; i++)

17
element = arr[i];

for(j=(i-1); j>=0 && arr[j]>element; j--)

arr[j+1] = arr[j];

arr[j+1] = element;

System.out.println("\nThe new sorted element using insertion sort is: ");

for(i=0; i<n; i++)

System.out.print(arr[i]+ " ");

18
Output:

Result:
Thus the above program was successfully executed and the output was
verified.

19
EX.NO:2(b) QUEUE USING DATA STRUCTURE

DATE:

Aim:

To Write a java program to develop queue data structure using class and
objects.

Algorithm:

Step 1: Start the program.

Step 2: Create a queue.

Step 3: Enter the limit values.

Step 4: If the Values in the limit is given.

Step 4.1: If the values are not in limit an error exit.

Do operation according to the elements.

Step 6: stop the program.

Program:

import java.io.*;

class QueueAction {

BufferedReader is = new BufferedReader(new


InputStreamReader(System.in));

int items[];

int i, front = 0, rear = 0, noOfItems, item, count = 0;

void getdata() {

try {

20
System.out.println("Enter the Limit :");

noOfItems = Integer.parseInt(is.readLine());

items = new int[noOfItems];

} catch (Exception e) {

System.out.println(e.getMessage());

void enqueue() {

try {

if (count < noOfItems) {

System.out.println("Enter Queue Element :");

item = Integer.parseInt(is.readLine());

items[rear] = item;

rear++;

count++;

} else {

System.out.println("Queue Is Full");

} catch (Exception e) {

System.out.println(e.getMessage());

21
}

void dequeue() {

if (count != 0) {

System.out.println("Deleted Item :" + items[front]);

front++;

count--;

} else {

System.out.println("Queue IS Empty");

if (rear == noOfItems) {

rear = 0;

void display() {

int m = 0;

if (count == 0) {

System.out.println("Queue IS Empty");

} else {

for (i = front; m < count; i++, m++) {

System.out.println(" " + items[i]);

22
}

class QueueProgram {

public static void main(String arg[]) {

DataInputStream get = new DataInputStream(System.in);

int choice;

QueueAction queue = new QueueAction();

queue.getdata();

System.out.println("Queue\n\n");

try {

do {

System.out.println("1.Enqueue\n2.Dequeue\n3.Display\n4.Exit\n");

System.out.println("Enter the Choice : ");

choice = Integer.parseInt(get.readLine());

switch (choice) {

case 1:

queue.enqueue();

break;

case 2:

queue.dequeue();

break;

case 3:

23
queue.display();

break;

} while (choice != 4);

} catch (Exception e) {

System.out.println(e.getMessage());

24
Output:

Result:
Thus the above program was successfully executed and the output was
verified.

25
EX.NO:3 EMPLOYEE DETAILS

DATE:

Aim:

To create a Java console application for employee payroll process


management. This project includes Employee and they further classified as
Programmer, Assistant Professor, Associate Professor, Professor.

Algorithm:

Step 1: Start the process.

Step 2: Prompt the user with converter choice 1. Programmer 2. Assistant

Professor 3. Associate Professor 4. Professor 5. Exit and get choice.

Step 3: If user selects a Programmer then proceed to step 4.

Step 4: Get the user details [Name, ID, Address, Mail ID and Mobile

Number] and goto step 5.

Step 5: Proceed to Programmers Payment Processing.

Step 5.1: Get the basic pay of Programmer.

Step 5.2: If user enters -1 assume basic pay as 30000 and goto step 15 .

Step 5.3: Else directly go to step 15.

Step 6: If user selects Assistant Professor step 7.

Step 7: Get the user details [Name, ID, Address, Mail ID and Mobile

Number] and goto step 8.

Step 8: Proceed to Assistant Professor Payment Processing.

Step 8.1: Get the basic pay of Assistant Professor.

Step 8.2: If user enters -1 assume basic pay as 25000 and goto step 15 .

Step 8.3: Else directly go to step 15.

26
Step 9: If user selects Associate Professor step 10.

Get the user details [Name, ID, Address, Mail ID and Mobile

Number] and goto step 11.

Step 11: Proceed to Associate Professor Payment Processing.

Step 11.1: Get the basic pay of Associate Professor.

Step 11.2 : If user enters -1 assume basic pay as 40000 and goto step 15 .

Step 11.3:Else directly go to step 15.

Step 12:If user selects Professor step 13.

Step 13: Get the user details [Name, ID, Address, Mail ID and Mobile

Number] and goto step 14 .

Step 14: Proceed to Professor Payment Processing.

Step 14.1:Get the basic pay of Professor.

Step 14.2:If user enters -1 assume basic pay as 70000 and goto step 15 .

Step 14.3: Else directly go to step 15.

Step 15: Compute Per_Day_Pay = original_basic_pay /

no_of_days_in_the_current_month.

Step 16: Get the number of days worked from user that include Cl, WH, FH

and exclude the LOP.

Step 17: Check no_days_worked <= no_of_days_in_the_current_month.

Else display “Error Message” and goto step 18.

Step 18: Compute Current_Basic_Pay = Per_Day_Pay * no_days_worked.

Step 19: Compute Following and Store.

DA = (Current_Basic_Pay/100) * 97.

HRA = (Current_Basic_Pay/100) * 12.

27
PF = (Current_Basic_Pay/100) * 0.1.

GROSS_PAY = Current_Basic_Pay + DA + HRA + PF


NET_PAY = GROSS_PAY – PF.

Step 20: Display Payment Details [Name, ID, Address, Mail ID, Mobile

Number, BASIC PAY, DA, HRA,PF,GROSS_PAY, NET_PAY].

Step 21: Stop Processing.

Program:

import java.util.*;

import java.io.*;

class Employee

String emp_name;

String emp_id;

String emp_address;

String emp_mail_id;

String emp_mobile_no;

int basic_pay;

int per_day_pay;

int current_basic_pay;

int da, hra, pf, gross_pay;

int net_pay;

int no_of_days_in_current_month;

int no_of_days_worked;

28
Calendar cal;

Scanner input;

Employee()

input = new Scanner(System.in);

cal = new GregorianCalendar();

no_of_days_in_current_month =

cal.getActualMaximum(Calendar.DAY_OF_MONTH);

getUserBasicDetails();

public void generatePaySlip()

this.da = (this.current_basic_pay / 100) * 97;

this.hra = (this.current_basic_pay / 100) * 12;

this.pf = (int) ((this.current_basic_pay / 100) * 0.1);

this.gross_pay = this.current_basic_pay + da + hra + pf;

this.net_pay = gross_pay - pf;

public void displayPaySlip()

System.out.println("Name: " + this.emp_name);

System.out.println("ID: " + this.emp_id);

System.out.println("Address: " + this.emp_address);

System.out.println("MailID: " + this.emp_mail_id);

29
System.out.println("Mobile No: " + this.emp_mobile_no);

System.out.println("\nEarnings");

System.out.println("--------");

System.out.println("BASIC Pay: " + current_basic_pay + " Rs");

System.out.println("DA : " + da + " Rs");

System.out.println("HRA : " + hra + " Rs");

System.out.println("\nDeductions");

System.out.println("----------");

System.out.println("PF : " + pf + " Rs");

System.out.println("GROSS Pay: " + gross_pay + " Rs");

System.out.println("NET Pay: " + net_pay + " Rs");

public void getUserBasicDetails()

System.out.println("Enter Details");

System.out.println("Name: ");

this.emp_name = input.next();

System.out.println("ID: ");

this.emp_id = input.next();

System.out.println("Address: ");

this.emp_address = input.next();

System.out.println("MailID: ");

this.emp_mail_id = input.next();

System.out.println("Mobile No:");

30
this.emp_mobile_no = input.next();

public void computeCurrentBasicPay(String empType)

this.per_day_pay = this.basic_pay / no_of_days_in_current_month;

System.out.println("\nBasic Pay of"+empType+"


"+this.basic_pay+"for"+this.no_of_days_in_current_month+"days");

System.out.println("This month this" + empType + "gets" + this.per_day_pay +


"INR as basic pay per day");

System.out.println("Enter no.of days worked by" + empType + "including CL,


WH,FH and excluding LWP:");

this.no_of_days_worked = input.nextInt();

if (no_of_days_worked <= no_of_days_in_current_month)

this.current_basic_pay = this.per_day_pay * no_of_days_worked;

System.out.println("Programmer");

System.out.println("----------");

generatePaySlip();

else {

System.out.println("Sorry Please Enter Valid Days");

protected void finalize()

31
input.close();

System.exit(0);

class Programmer extends Employee

public Programmer()

super();

computeProgrammerPay();

public void computeProgrammerPay()

System.out.println("Enter Basic pay of Programmer [enter -1 for Default [BP


=30000]]:");

this.basic_pay = input.nextInt();

if (this.basic_pay == -1)

this.basic_pay = 30000;

System.out.println("Default Pay Taken");

computeCurrentBasicPay("Programmer");

generatePaySlip();

displayPaySlip();

32
}

class AssistantProfessor extends Employee

public AssistantProfessor()

super();

computeAssistantProfessorPay();

public void computeAssistantProfessorPay()

System.out.println("Enter Basic pay of AssistantProfessor [enter -1 for Default


[BP= 25000]]:");

this.basic_pay = input.nextInt();

if (this.basic_pay == -1) {

this.basic_pay = 25000;

System.out.println("Default Pay Taken");

computeCurrentBasicPay("AssistantProfessor");

generatePaySlip();

displayPaySlip();

class AssociateProfessor extends Employee

33
public AssociateProfessor()

super();

computeAssociateProfessorPay();

public void computeAssociateProfessorPay()

System.out.println("Enter Basic pay of AssociateProfessor [enter -1 for Default


[BP= 40000]]:");

this.basic_pay = input.nextInt();

if (this.basic_pay == -1) {

this.basic_pay = 40000;

System.out.println("Default Pay Taken");

computeCurrentBasicPay("AssociateProfessor");

generatePaySlip();

displayPaySlip();

class Professor extends Employee

public Professor() {

super();

computeProfessorPay();

34
public void computeProfessorPay()

System.out.println("Enter Basic pay of Professor [enter -1 for Default [BP


=70000]]:");

this.basic_pay = input.nextInt();

if (this.basic_pay == -1) {

this.basic_pay = 70000;

System.out.println("Default Pay Taken");

computeCurrentBasicPay("Professor");

generatePaySlip();

displayPaySlip();

public class ex3

public static void main(String[] args) throws IOException

Programmer aProgrammer;

AssistantProfessor aAssistantProfessor;

AssociateProfessor aAssociateProfessor;

Professor aProfessor;

String choice;

int n_choice = 0;

Scanner userInput = new Scanner("System.in");

35
while (n_choice != 5) {

System.out.println("\n\nEmployee Payroll System");

System.out.println("***********************\n");

System.out.println("1. Programmer\n2. Assistant Professor\n" + "3. Associate


Professor\n4. Professor\n"+ "5. Exit\n\nEnter Your Choice");

choice = new BufferedReader(new InputStreamReader(System.in)).readLine();

n_choice = Integer.parseInt(choice);

switch (n_choice) {

case 1:

System.out.println("Programmer Selected");

aProgrammer = new Programmer();

break;

case 2:

System.out.println("AssistantProfessor Selected");

aAssistantProfessor = new AssistantProfessor();

break;

case 3:

System.out.println("AssociateProfessor Selected");

aAssociateProfessor = new AssociateProfessor();

break;

case 4:

System.out.println("Professor Selected");

aProfessor = new Professor();

case 5:

System.out.println("Thank You !!!");

36
userInput.close();

break;

default:

System.out.println("Enter valid choice !!!");

break;

37
Output:

38
Result:
Thus the above program was successfully executed and the output was
verified.

39
EX.NO:4 ABSTRACT CLASS

DATE:

Aim:

To create a Java console application to find the area of different shapes


using abstract class concept in java.

Algorithm:

Step 1: Start the Process.

Step 2: Prompt user with List Operation Choices.

1.Rectangle 2.Triangle 3.Circle 4.Exit, Get the choice from user.

Step 3: If user selects Rectangle.

Step 3.1: Get the Length and Breath from the user.

Step 3.2: Compute Area = Length * Breath.

Step 3.3: Display Area.

Step 4: If user selects Triangle.

Step 4.1: Get the Length and Height from the user.

Step 4.2: Compute Area = Length * Height * 0.5.

Step 4.3: Display Area.

Step 5: If user selects Circle.

Step 5.1: Get the Radius of the Circle.

Step 5.2: Compute Area = 3.14 * Radius * Radius.

Step 5.3: Display Area.

Step 6: If user selects exit end the process.

Step 7: Stop the Process.

40
Program:

import java.util.Scanner;

abstract class Shape {

double length = 0.0;

double hight = 0.0;

public abstract void printArea();

class Rectangle extends Shape {

double area = 0.0;

public void printArea() {

System.out.println("\nRectangle");

System.out.println("---------\n");

Scanner input = new Scanner(System.in);

System.out.println("Enter Length of Rectangle : ");

this.length = input.nextDouble();

System.out.println("Enter Breadth of Rectangle : ");

this.hight = input.nextDouble(); this.area = this.length * this.hight;


System.out.println("Area of the Rectangle is : " + this.area);

class Triangle extends Shape {double area = 0.0;

public void printArea() {

41
System.out.println("\nTriangle");

System.out.println("---------\n");

Scanner input = new Scanner(System.in);

System.out.println("Enter Length of Triangle : ");

this.length = input.nextDouble();

System.out.println("Enter Hight of Triangle : ");

this.hight = input.nextDouble(); this.area = 0.5 * this.length * this.hight;


System.out.println("Area of the Triangle is : " + this.area);

class Circle extends Shape {

double area = 0.0;

public void printArea() {

System.out.println("\nCircle");

System.out.println("-------\n");

Scanner input = new Scanner(System.in);

System.out.println("Enter Radius of Circle : ");

this.length = input.nextDouble();

this.area = Math.PI * this.length * this.length;

System.out.println("Area of the Circle is : " + this.area);

class area1

42
{

public static void main(String[] args)

Scanner userInput = new Scanner(System.in);

int choice = 0;

do

System.out.println("Finding Area");

System.out.println("************");

System.out.println(

"\n1. Rectangle" + "\n2. Triangle" + "\n3. Circle" + "\n4. Exit"+ "\n\nEnter your
choice: ");

choice = userInput.nextInt();

switch (choice)

case 1:

Shape rt = new Rectangle();

rt.printArea();

break;

case 2:

Shape tr = new Triangle();

tr.printArea();

break;

43
case 3:

Shape cr = new Circle();

cr.printArea();

break;

case 4:

System.out.println("\n\nThank You !!!");

userInput.close();

break;

default:

System.out.println("Please enter valid input");

break;

} while (choice != 4);

44
Output:

45
Result:
Thus the above program was successfully executed and the output was
verified.

46
EX.NO:5 INTERFACE

DATE:

Aim:

To write a java program to implement an interface and finding the area of


shapes.

Algorithm:

Step 1: Start the Process

Step 2: Define interface area pi=3.14 and double calc(double x,double y).

Step 3: Create rect class and implements area and return x*y.

Step 4: Create tri class and implements area and return 0.5*x*y.

Step 5: Create cir class and implements area and return pi*x*x.

Step 6: Display menu and get the choice.

Step 6.1: If Choice ==1 then goto step 2.

Step 6.2: If choice ==2 then goto step 3.

Step 6.3: If choice ==3 then goto step 4.

Step 6.4: If choice ==4 then display thankyou.

Step 7: Stop the process.

Program:

import java.util.*;

interface Area2

double pi=3.14;

47
double calc(double x,double y);

class rect implements Area2

public double calc(double x,double y)

return x*y;

class tri implements Area2

public double calc(double x,double y)

return 0.5*x*y;

class cir implements Area2

public double calc(double x,double y)

return pi*x*y;

48
public class interface1

public static void main(String args[])

Scanner in=new Scanner(System.in);

int choice = 0;

do

System.out.println("\n1.retangle\n2.triangle\n3.circle\n4.exit");

System.out.println("enter your choice:");

choice = in.nextInt();

switch(choice)

case 1:rect r=new rect();

System.out.println("enter the length of rectangle");

double len=in.nextDouble();

System.out.println("area of breadth of rectangle");

double bread=in.nextDouble();

System.out.println("area of rectangle is"+r.calc(len,bread));

break;

case 2:tri t=new tri();

System.out.println("enter the breadth of triangle");

double b=in.nextDouble();

49
System.out.println("enter the height of triangle");

double h=in.nextDouble();

System.out.println("enter the aver of triangle is"+t.calc(b,h));

case 3:cir c=new cir();

System.out.println("enter the radius of rectangle of circle");

double rad=in.nextDouble();

System.out.println("aver of circle is"+c.calc(rad,rad));

break;

case 4:System.out.println("thankyou!!!");

in.close();

break;

default:System.out.println("enter valid choice");

break;

}while(choice!=4);

50
Output:

51
52
Result:

Thus the above program was successfully executed and the output was
verified.

53
EX.NO:6(a) EXCEPTION HANDLING

DATE:

Aim:

To write a java program to implement an integer with out of range using


exception handling.

Algorithm:

Step 1: Start the program.

Step 2: Create a class name student and put string count “y”.

Step 3: Then,Try the Mark statement. The Mark form 0 to 100 and Thow the
new argument.

Step 4: And catch the illegal argument exception and print the count.

Step 5: Finally the value is out of encountered then move next case ‘Y’.

Step 6: stop the program.

Program:

import java.util.Scanner;

public class Student {

public static void main(String[] args) {

String cont = "y";

run(cont);

static void run(String cont) {

54
Scanner scan = new Scanner(System.in);

while( cont.equalsIgnoreCase("y")) {

try {

System.out.println("Enter an integer: ");

int marks = scan.nextInt();

if (marks < 0 || marks > 100)

throw new IllegalArgumentException("value must be non-


negative and below 100");

System.out.println( marks);

catch(IllegalArgumentException i) {

System.out.println("out of range encouneterd. Want to continue");

cont = scan.next();

if(cont.equalsIgnoreCase("Y"))

run(cont);

55
Output:

Result:

Thus the above program was successfully executed and the output was
verified.

56
EX.NO:6(b) USER DEFINED EXCEPTION

DATE:

Aim:

To create a java application for banking transaction system that helps the user
to do their credit and debit transactions and it rises user defined exception while
encountering errors in transaction and also it should be solved using exception
handling techniques.

Algorithm:

Step 1: Start the Process

Step 2: Promt user with list operations choices

1.add money 2.Get money 3.Details 4.exit.

Get the choice from user.

Step 3: If user selects add money.

Step 3.1: Get the amount to be added to balance from the user

Step 3.2: If the amount is less than 0 throw invalid credit exception

‘ and goto step 3.4.

Step 3.3: Else add amount to balance and goto step 2.

Step 3.4: Prompt user with “enter valid credit amount”.

Step 4: If user select get money.

Step 4.1: get the amount to be debited to balance from the user.

Step 4.2: If the amount is greater then existing balance then throw

Invalid debit exception.

Step 4.3: Else detect amount from balance and goto step 2.

57
Step 4.4: Prompt user with “enter the valid debit amount”.

Step 5: If user selects details then display customers details[Name,Account

Number,Current balance].

Step 6: If user wants to exit display “Thankyou !!!”.

Step 7: Stop the process.

Program:

import java.util.Scanner;
class Customer
{
String name;
int accNo;
int balance;
public Customer(String name, int accNo)
{
this.name = name;
this.accNo = accNo;
this.balance = 0;
}
public void creditTransaction(int amount)
{
Scanner input = new Scanner(System.in);
try
{
if (amount < 0)
throw new InvalidCredit();
else
balance = balance + amount;
}
catch (InvalidCredit e)
{
amount = input.nextInt();
creditTransaction(amount);
}
}
public void debitTransaction(int amount)

58
{
Scanner input = new Scanner(System.in);
try
{
if (amount > balance)
throw new InvalidDebit();
else
balance = balance - amount;
}
catch (InvalidDebit e)
{
amount = input.nextInt(); debitTransaction(amount);
}}
public void displayDetails()
{
System.out.println("Customer Details");
System.out.println("****************");
System.out.println("Customer Name : "+this.name);
System.out.println("Customer AccNo : "+this.accNo);
System.out.println("Customer Current Balance : "+this.balance);
}}
class InvalidCredit extends Exception
{
public InvalidCredit()
{
System.out.print("Please enter valid credit amount")

59
}}
C
lass InvalidDebit extends Exception
{
public InvalidDebit()
{
System.out.print("Please enter valid debit amount");
}}
public class except
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String name;
int acc_no;
System.out.println("Enter Customer Name");
name = input.next();
System.out.println("Enter account number");
acc_no = input.nextInt();
Customer aCustomer = new Customer(name, acc_no);
int choice = 0;
while(choice != 4)
{
System.out.println("\n1. Add Money\n2. Get Money\n3. Details\n4. Exit");
choice = input.nextInt();
switch(choice)
{
case 1:
System.out.println("Enter the amount");
aCustomer.creditTransaction(input.nextInt());
break;
case 2:
System.out.println("Enter the amount");
aCustomer.debitTransaction(input.nextInt());
break;
case 3:
aCustomer.displayDetails();
break;
case 4:
System.out.println("Thank You !!!");

60
break;
}
}
}
}

61
OUTPUT:

62
Result:

Thus the above program was successfully executed and the output was
verified.

63
EX.NO:7 MULTITHREADING

DATE:

Aim:

To create a java console application the uses of the multithreading concepts


in java. The application has 3 threads one creates random number one for square and
one for cube.

Algorithm:

Step 1: Start the Process

Step 2: Create a thread for random number.

Step 3: Obtain one random number and check is odd or even.

Step 3.1: If number is even then create and start thread that computes

Square of a number.

Step 3.2: Compute number*number and display the answer.

Step 3.3: Notify to random number thread and goto step 4.l

Step 4: Wait for 1 second and continue to step 3 until user wants to exit.

Step 5: Stop the program.

Program:

import java.util.*;

class RandomNumberThread extends Thread{

Random num = new Random();

int value;

public void run(){

64
while(true){

try{

this.sleep(1000);

}catch(InterruptedException e){}

value = num.nextInt(1000);

System.out.println("RandomNumberThread generated a number :"+value);

if(value%2==0){

new SquareGenThread(value).start();

else{

new CubeGenThread(value).start();

class SquareGenThread extends Thread{

int number,square;

public SquareGenThread(int number){

this.number = number;

public void run(){

try{

65
this.sleep(3000);

}catch(InterruptedException e){}

this.square = this.number*this.number;

System.out.println("SquareGenThread-->Square of"+number+"is "+square);

class CubeGenThread extends Thread{

int number,square;

public CubeGenThread(int number){

this.number = number;

public void run(){

try{

this.sleep(2000);

}catch(InterruptedException e){}

this.square = this.number*this.number*this.number;

System.out.println("CubeGenThread-->Square of"+number+"is "+square);

public class MultiThreading {

public static void main(String[] args) {

new RandomNumberThread().start();

}}

66
Output:

Result:

Thus the above program was successfully executed and the output was
verified.

67
EX.NO:8 FILE OPERATIONS

DATE:

Aim:

To write a java program to perform file operations (Create,Delete,

Read,Write).

Algorithm:

Step 1: Start the program.

Step 2: Import the java packages, by using Scanner class get the input.

Step 3: Create a File object associated with the file or directory specified by

pathname.

Step 4: By the pathname exists, Returns the file denoted by the pathname

Exists, false otherwise

Step 5: The canRead() checks whether the application can read the file

Step 5.1: The canWrite() checks whether the application can modify to

the file

Step 6: The getAbsolutePath() returns the absolute pathname

Step 7: Stop the program.

Program:

import java.io.*; import java. util.*; public class FileInfo

public static void main(String[] args) throws IOException

68
{

Scanner in=new Scanner(System.in);

System.out.print("\nEnter the FileName: "); String fName = in.next();

File f = new File(fName);

String result = f.exists() ? " exists." : " does not exist."; System.out.println("\nThe
given file " +fName + result);

System.out.println("\nFile Location: "+f.getAbsolutePath()); if(f.exists())

result = f.canRead() ? "readable." : "not readable."; System.out.println("\nThe file is


" + result);

result = f.canWrite() ? "writable." : "not writable."; System.out.println("\nThe file is


" + result);

System.out.println("\nFile length is " + f.length() + " in bytes.");

if (fName.endsWith(".jpg") || fName.endsWith(".gif") || fName.endsWith(".png"))

System.out.println("\nThe given file is an image file.");

else if (fName.endsWith(".pdf"))

System.out.println("\nThe given file is an portable document format.");

69
else if (fName.endsWith(".txt"))

System.out.println("\nThe given file is a text file.");

else

System.out.println("The file type is unknown.");

70
Output:

71
Result:

Thus the above program was successfully executed and the output was
verified.

72
EX.NO:9(a) GENERIC CLASSES

DATE:

Aim:

To wite a java program for generic classes and generic methods.

Algorithm:

Step 1: Start The program.

Step 2: Import packages.

Step 2.1: Compare order the objects of user-defined class.

Step 3: Package contains only one method named compareTo(Object).

Step 4: The compareTo() method works by returning an int value that is either
positive, negative, or zero.

Step 5: Create a generic method max(), that can accept any type of argument.

Step 6: Finally the function returns an element which has the maximum

value.

Step 6.1: We can call generic method by passing with different types of

Arguments.

Step 7: Stop the program.

Program:

package genclass;

import java.util.*;

import java.io.*;

73
class Arr<T>{

public ArrayList<T>obj;

public Arr(int size){

obj=new ArrayList<T>(size);

public void insert(int index,T item){

obj.add(index,item);

public void display(){

System.out.print(" "+obj);

public T delete(int index){

return obj.remove(index);

public class Genclass{

public static void main(String[] args) {

int[] iArray={1,2,3,4,5};

Arr<Integer>iobj=new Arr<Integer>(10);

int i,index;

System.out.println("\n Array of an Integer...");

for(i=0;i<5;i++){

iobj.insert(i,iArray[i]);

74
}

iobj.display();

System.out.println("\nInserting the elements in integer Array");

Scanner sc=new Scanner(System.in);

int item=sc.nextInt();

System.out.println("Enter the index at which the element is to be inserted");

System.out.println("Enter the element to be inserted");

index=sc.nextInt();

iobj.insert(index,item);

iobj.display();

System.out.println("\nEnter the index of the element to be deleted");

index=sc.nextInt();

iobj.delete(index);

iobj.display();

double[]dArray={11.11,22.22,33.33,44.44,55.55};

Arr<Double>dobj=new Arr<Double>(10);

System.out.println("\nArray of double is...");

for(i=0;i<5;i++){

dobj.insert(i,dArray[i]);

dobj.display();

System.out.println("\nInserting the elements in double Array");

System.out.println("Enter the element to be inserted");

75
double ditem=sc.nextDouble();

System.out.println("Enter the index at which the element is to be inserted");

index=sc.nextInt();

dobj.insert(index,ditem);

dobj.display();

System.out.println("\nEnter the index of the element to be deleted");

index=sc.nextInt();

dobj.delete(index);

dobj.display();

76
Output:

Result:

Thus the above program was successfully executed and the output was
verified.

77
EX.NO:9(b) GENERIC METHOD

DATE:

Aim:

To wite a java program for generic classes and generic methods.

Algorithm:

Step 1: Start The program.

Step 2: Import packages.

Step 2.1: Compare order the objects of user-defined class.

Step 3: Package contains only one method named compareTo(Object).

Step 4: The compareTo() method works by returning an int value that is


either positive, negative, or zero.

Step 5: Create a generic method max(), that can accept any type of
argument.

Step 6: Finally the function returns an element which has the maximum

value.

Step 6.1: We can call generic method by passing with different types of

Arguments.

Step 7: Stop the program.

78
Program:

package genmeth;

class gen{

public<E extends Comparable <E>> void bubblesortg(E[]Arr){

E temp;

for(int i=1;i<Arr.length;i++){

for(int j=0;j<Arr.length-i;j++){

if(Arr[j].compareTo(Arr[j+1])>0){

temp=Arr[j];

Arr[j]=Arr[j+1];

Arr[j+1]=temp;

for(E i:Arr){

System.out.print(" "+i);

public class Genmeth {

public static void main(String[] args) {

79
Integer a[]={34,56,78,67,11};

System.out.println("After sorting the array");

gen s=new gen();

s.bubblesortg(a);

Double d[]={3.4,54.6,78.9,12.4,2.4};

System.out.println("\nAfter sorting the array");

s.bubblesortg(d);

80
Output:

Result:

Thus the above program was successfully executed and the output was
verified.

81
EX.NO:9(c) GENERIC MAX FINDER

DATE:

Aim:

To create a Java console application that finds the maximum in a array based
on the type of the elements using generic functions in java.

Algorithm:

Step 1: Start the Process

Step 2: Create a array of number and array of strings and pass it to generic
function

Step 3: If the array is Integer type

Step 3.1: Assume first element as MAX

Step 3.2: Compare [Numeric Perspetive] this element with MAX

Step 3.3: If it is greater than MAX then store current element as MAX

Step 3.4: Else do nothing

Step 3.5: Goto step 3.1 until all the elements has been processed.

Step 4: If the array is String type

Step 4.1: Assume first element as MAX

Step 4.2: Compare [Dictionary Perspective] this element with MAX

Step 4.3: If it is greater than MAX then store current element as MAX

Step 4.4: Else do nothing

82
Step 4.5: Goto step 3.1 until all the elements has been processed.

Step 5: Stop the Process

Program:

class GenericMax
{
public <T extends Comparable<T>>
void maxFinder (T[] array){ T max = array[0];
for(T element: array)
{
System.out.println(element);
if(element.compareTo(max) > 0)
max = element;
}
System.out.println("Max is : "+max);
}
}
public class gener
{
public static void main(String[] args)
{
GenericMax max = new GenericMax();
Integer[] numbers = {14,3,42,5,6,10};
String[] strings = {"R","Ra","Raj"};
max.maxFinder(numbers);
max.maxFinder(strings);
}
}

83
Output:

Result:

Thus the above program was successfully executed and the output was
verified.

84
EX.NO:10 JAVA FX APPLICATION

DATE:

Aim:

To create java Fx application to implement controls,layout and menus.

Algorithm:

Step 1: Start the program

Step 2: Import required classes

Step 3:Extending JFrame class and

Implementing ItemListener interface

Step 4: Setting the buttons for the layout

Step 5: Assign the name to buttons declared above

Step 6: To add window and to change the colors of traffic signal

Step 7: Create a Button Group such that it contains three radio buttons Red,

Yellow, Green

Step 7.1: When red is clicked you want to display “Stop”

Step 7.2: When orange is clicked you want to display “ready”

Step 7.3: When the green button is clicked Display “Go”

Step 8: Also create a sample Traffic signal demo using rectangle and ovals

using 2D graphics

Step 9: Setting size and making traffic signal

Step 10: Stop the program

85
Program:

/*

* To change this license header, choose License Headers in Project Properties.

* To change this template file, choose Tools | Templates

* and open the template in the editor.

*/

package javafxapplication4;

import javafx.application.Application;

import static javafx.application.Application.launch;

import javafx.event.ActionEvent;

import javafx.event.EventHandler;

import javafx.scene.Scene;

import javafx.scene.control.TextField;

import javafx.scene.control.Button;

import javafx.scene.control.ToggleButton;

import javafx.scene.control.Label;

import javafx.scene.layout.GridPane;

import javafx.stage.Stage;

/**

86
* @author Admin Is User

*/

public class JavaFXApplication4 extends Application {

GridPane root=new GridPane();

Label l1=new Label("Enter the Consumer No");

TextField cno=new TextField();

Label l2=new Label("Enter the Consumer Name");

TextField cname=new TextField();

Label l3=new Label("Enter the Previous Reading:");

TextField pre=new TextField();

Label l4=new Label("Enter the Current Reading");

TextField cr=new TextField();

Label val=new Label("BIll AMOUNT");

TextField b=new TextField();

87
Label l5=new Label("Enter the Type of Connection(Com/Dom):");

TextField con=new TextField();

ToggleButton dom=new ToggleButton("Domestic");

ToggleButton com=new ToggleButton("Commercial");

@Override

public void start(Stage primaryStage) {

root.setHgap(5);

root.addRow(0,l1,cno);

root.addRow(1,l2,cname);

root.addRow(2,l3,pre);

root.addRow(3,l4,cr);

root.addRow(4,l5,dom,com);

root.addRow(6,val,b);

dom.setOnAction(e->Calcdom());

com.setOnAction(e->Calculatebill());

Scene scene = new Scene(root, 600, 350);

primaryStage.setTitle("Electricity Bill Calculator");

primaryStage.setScene(scene);

primaryStage.show();

88
}

public void Calcdom(){

double consumerno=Double.parseDouble(cno.getText());

String Consumername=cname.getText();

double previous_reading=Double.parseDouble(pre.getText());

double current_reading=Double.parseDouble(cr.getText());

bill ba=new
bill(current_reading,previous_reading,Consumername,consumerno);

b.setText(String.format("%.2f",ba.gettotaldombill()));

}public void Calculatebill(){

double consumerno=Double.parseDouble(cno.getText());

String Consumername=cname.getText();

double previous_reading=Double.parseDouble(pre.getText());

double current_reading=Double.parseDouble(cr.getText());

bill ba=new
bill(current_reading,previous_reading,Consumername,consumerno);

b.setText(String.format("%.2f",ba.gettotalcombill()));

89
}

public void result(){

public static void main(String[] args) {

launch(args);

class bill implements java.io.Serializable{

double conno;

String conname;

double preread;

double currentread;

public bill(double currentread,double preread,String name,double cno){

this.currentread=currentread;

this.preread=preread;

this.conname=name;

this.conno=cno;

public double getcurrentread(){

90
return currentread;

public double getpreread(){

return preread;

public String getconname(){

return conname;

public double geetconno(){

return conno;

public double gettotaldombill(){

double bill;

double currentreading=currentread-preread;

if(currentreading>=0 && currentreading<=100)

bill =currentreading*1;

else if(currentreading>100 && currentreading<=200)

bill =(100*1)+((currentreading-100)*2.50);

else if(currentreading>200 && currentreading<=500)

bill =(100*1)+(100*2.50)+((currentreading-200)*4);

else

bill=(100*1)+(100*2.50)+(300*4)+((currentreading-500)*6);

91
return bill;

public double gettotalcombill(){

double bill;

double currentreading=currentread-preread;

if(currentreading>=0 && currentreading<=100)

bill =currentreading*2;

else if(currentreading>100 && currentreading<=200)

bill =(100*2)+((currentreading-100)*4.50);

else if(currentreading>200 && currentreading<=500)

bill =(100*2)+(100*4.50)+((currentreading-200)*6);

else

bill=(100*2)+(100*4.50)+(300*6)+((currentreading-500)*7

return bill;

92
Output:

Result:

Thus the above program was successfully executed and the output was
verified.

93
CONTENT BEYOND SYLLABUS
IMPLEMENTATION OF JDBC

Aim:

To develop a simple OPAC system for library using event-driven and


concurrent programming paradigms of Java. Use JDBC to connect to a back-end
database.

Algorithm:

Step 1: Create a Database

Step 2: Create a table employee in Database created

Step 3: Insert the fields into the employee table with the following fields: name,
rollno, course, subject, marks.

Step 4: Create another panel consisting of buttons UserID, BookID,


Return/Renewal,Fine.

Step 5: Associate these buttons with listeners(with Transaction Database).

PROGRAM:

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JdbcOdbcExample
{
public static void main(String args[])
{
Connection con = null;
PreparedStatement stmt = null;

94
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:swing");
String sql ="INSERT INTO employee (name, rollNo, course, subject, marks)
VALUES" +
"('Deepak', 10, 'MCA', 'Computer Science', 85)";
stmt = con.prepareStatement(sql);
int i = stmt.executeUpdate();
if(i > 0 )
{
System.out.println("Record Added Into Table Successfully.");
}
} catch (SQLException sqle) {
System.out.println(sqle.getNextException());
} catch (ClassNotFoundException e) {
System.out.println(e.getException());
} finally {
try {
if (stmt != null) {
stmt.close();

stmt = null;
}
if (con != null) {
con.close();
con = null;
}
} catch (Exception e) {
System.out.println(e);
}
}
}
}

95
OUTPUT:

Table Before inserting the record into it

Result:

Thus the above program was successfully executed and the output was
verified.

96
APPLICATION USING JAVA AWT PACKAGES

AIM:

To create a Java GUI application that mimics the basic and advanced
functionalities of a scientific calculator.

ALGORITHM:

Step 1: Start the Process

Step 2: Display Text View and Number Pad and Option Pads

Step 3: If user presses any number get the existing numbers in Text View add
them up and display

Step 4: If user press Operators

Step 4.1 Get the Text View content as Operant 1 and Set the display to null.

Step 4.2 If user pressed “+” button set operator as plus

Step 4.3 If user pressed “-” button set operator as minus

Step 4.4 If user pressed “x” button set operator as multiply

Step 4.5 If user pressed “/” button set operator as divide

Step 4.6 Goto step 3

Step 5 If: user pressed “=” button then proceed following steps.

Step 5.1: Get the Text View content as Operant 2 and Set the display to null.

Step 5.2: If operator is “plus” then display Text View as Operant 1 +


Operant 2

Step 5.3: If operator is “minus” then display Text View as Operant 1 -


Operant 2

97
Step 5.4: If operator is “multiply” then display Text View as Operant 1 *
Operant

Step 5.5: If operator is “divide” then display Text View as Operant 1 /


Operant 2

Step 5.6: Goto step 4

Step 6: If advanced button pressed

Step 6.1: Change Operant Types [+,-,x,/ into sin, cos, tan, log] and goto step
2

Step 7: If user pressed any of the operator

Step 7.1: Get the Text View content as Operant 1 and Set the display to null.

Step 7.2: If user pressed “sin” button set display the sin value of Operant 1

Step 7.3: If user pressed “cos” button set display the cos value of Operant 1

Step 7.4: If user pressed “tan” button set display the tan value of Operant 1

Step 7.5: If user pressed “log” button set display the log value of Operant 1

Step 7.6: Goto step 7

Step 8: If advanced pressed again then revert the button changes and return back to
normal

Step 9: Repeat the process until user presses the close button then Stop the
Process.

PROGRAM:

import java.awt.*;
import java.awt.event.*;

98
class Numpan extends Panel implements ActionListener
{
Button n0,n1,n2,n3,n4,n5,n6,n7,n8,n9,point,equal;
Button plus,minus,multiply, divide;
Button m_plus,m_minus,clear,advanced;
TextField display;
String op1,op2,result;
String op_flag;
String data;
double dop1,dop2,dresult;
boolean flag_advanced=true;
public Numpan(TextField display)
{
this.display = display;
setLayout(new GridLayout(0,4));
n0 = new Button("0");
n0.setActionCommand("zero");
n0.addActionListener(this);
n1 = new Button("1");
n1.setActionCommand("one");
n1.addActionListener(this);
n2 = new Button("2");
n2.setActionCommand("two");
n2.addActionListener(this);
n3 = new Button("3");
n3.setActionCommand("three");
n3.addActionListener(this);
n4 = new Button("4");
n4.setActionCommand("four");
n4.addActionListener(this);
n5 = new Button("5");
n5.setActionCommand("five");
n5.addActionListener(this);
n6 = new Button("6");
n6.setActionCommand("six");
n6.addActionListener(this);
n7 = new Button("7");
n7.setActionCommand("seven");
n7.addActionListener(this);
n8 = new Button("8");

99
n8.setActionCommand("eight");
n8.addActionListener(this);
n9 = new Button("9");
n9.setActionCommand("nine");
n9.addActionListener(this);
point = new Button(".");
point.setActionCommand("point");
point.addActionListener(this);
equal = new Button("=");
equal.setActionCommand("equal");
equal.addActionListener(this);
plus = new Button("+");
plus.setActionCommand("plus");
plus.addActionListener(this);
minus = new Button("-");
minus.setActionCommand("minus");
minus.addActionListener(this);
multiply = new Button("x");
multiply.setActionCommand("multiply");
multiply.addActionListener(this);
divide = new Button("/");
divide.setActionCommand("divide");
divide.addActionListener(this);
m_plus = new Button("M+");
m_plus.setActionCommand("m_plus");
m_plus.addActionListener(this);
m_minus = new Button("M-");
m_minus.setActionCommand("m_minus");
m_minus.addActionListener(this);
clear = new Button("C");
clear.setActionCommand("clear");
clear.addActionListener(this);
advanced = new Button("ADV");
advanced.setActionCommand("advanced");
advanced.addActionListener(this);
add(m_plus);
add(m_minus);
add(clear);
add(advanced);
add(n1);

100
add(n2);
add(n3);
add(plus);
add(n4);
add(n5);
add(n6);
add(minus);
add(n7);
add(n8);
add(n9);
add(multiply);
add(point);
add(n0);
add(equal);
add(divide);
}
public String getDisplayText(){
return display.getText().toString();
}
public void setDisplay(String text){
display.setText(text);
}
public void clearDisplay(){
System.out.println("Clear Called");
setDisplay("");
data = "";
}
public void changeAdvanced(boolean toAdvanced)
{
if(toAdvanced){
plus.setLabel("sin");
plus.setActionCommand("sin");
minus.setLabel("cos");
minus.setActionCommand("cos");
multiply.setLabel("tan");
multiply.setActionCommand("tan");
divide.setLabel("log");
divide.setActionCommand("log");
}
else

101
{
plus.setLabel("+");
plus.setActionCommand("plus");
minus.setLabel("-");
minus.setActionCommand("minus");
multiply.setLabel("x");
multiply.setActionCommand("multiply");
divide.setLabel("/");
divide.setActionCommand("divide");
}
}
public void actionPerformed(ActionEvent e)
{
data = getDisplayText();
switch(e.getActionCommand())
{
case "zero":
setDisplay(data+"0");
break;
case "one":
setDisplay(data+"1");
break;
case "two":
setDisplay(data+"2");
break;
case "three":
setDisplay(data+"3");
break;
case "four":
setDisplay(data+"4");
break;
case "five":
setDisplay(data+"5");
break;
case "six":
setDisplay(data+"6");
break;
case "seven":
setDisplay(data+"7");
break;

102
case "eight":
setDisplay(data+"8");
break;
case "nine":
setDisplay(data+"9");
break;
case "plus":
op1 = data;
op_flag = "plus";
clearDisplay();
break;
case "minus":
op1 = data;
op_flag = "minus";
clearDisplay();
break;
case "multiply":
op1 = data;
op_flag = "multiply";
clearDisplay();
break;
case "divide":
op1 = data;
op_flag = "divide";
clearDisplay();
break;
case "clear":
clearDisplay();
break;
case "advanced":
if(flag_advanced)
{
changeAdvanced(true);
flag_advanced = false;
}
else
{
changeAdvanced(false);
flag_advanced = true;
}

103
break;
case "sin":
op1 = data;
setDisplay(String.valueOf(Math.sin(Double.valueOf(op1))));
break;
case "cos":
op1 = data;
setDisplay(String.valueOf(Math.cos(Double.valueOf(op1))));
break;
case "tan":
op1 = data;
setDisplay(String.valueOf(Math.tan(Double.valueOf(op1))));
break;
case "log":
op1 = data;
setDisplay(String.valueOf(Math.log(Double.valueOf(op1))));
break;
case "equal":
switch(op_flag)
{
case "plus":
op2 = data;
clearDisplay();
dop1 = Double.parseDouble(op1);
dop2 = Double.parseDouble(op2);
dresult = dop1 + dop2;
result = String.valueOf(dresult);
setDisplay(result);
op_flag = "";
break;
case "minus":
op2 = data;
clearDisplay();
dop1 = Double.parseDouble(op1);
dop2 = Double.parseDouble(op2);
dresult = dop1 - dop2;
result = String.valueOf(dresult);
setDisplay(result);
op_flag = "";
break;

104
case "multiply":
op2 = data;
clearDisplay();
dop1 = Double.parseDouble(op1);
dop2 = Double.parseDouble(op2);
dresult = dop1 * dop2;
result = String.valueOf(dresult);
setDisplay(result);
op_flag = "";
break;
case "divide":
op2 = data;
clearDisplay();
dop1 = Double.parseDouble(op1);
dop2 = Double.parseDouble(op2);
dresult = dop1 / dop2;
result = String.valueOf(dresult);
setDisplay(result);
op_flag = "";
break;
}
}}
}
class Calculator extends Frame
{
TextField display;
public Calculator() {
display = new TextField();
display.setFont(new Font("Times New Roman", Font.BOLD, 50)); setLayout(new
BorderLayout());
add(new Numpan(display),BorderLayout.CENTER);
add(display,BorderLayout.NORTH);
setVisible(true);
setSize(500,500);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
}

105
}
public class calc{
public static void main(String[] args) {
new Calculator();
}}

OUTPUT:

106
107
Result:

Thus the above program was successfully executed and the output was
verified.

108
109

You might also like