Oops Manualfinal
Oops Manualfinal
DATE:
Aim:
Algorithm:
Step 5: If key element is found, return the index position of the array
element.
Program:
import java.util.Scanner;
class linearsearch
n = in.nextInt();
1
array = new int[n];
array[c] = in.nextInt();
search = in.nextInt();
break;
2
Output:
Result:
Thus the above program was successfully executed and the output was
verified.
3
EX.NO:1(b) BINARY SEARCH
DATE:
Aim:
Algorithm:
End_value/2.
Program:
import java.util.Scanner;
class binary
n = in.nextInt();
4
System.out.println("Enter " + n + " integers");
array[c] = in.nextInt();
search = in.nextInt();
first = 0;
last = n - 1;
first = middle + 1;
break;
else
last = middle - 1;
5
Output:
Result:
Thus the above program was successfully executed and the output was
verified.
6
EX.NO:1(c) SELECTION SORT
DATE:
Aim:
Algorithm:
Program:
import java.util.Scanner;
size = scan.nextInt();
7
for(i=0; i<size; i++)
arr[i] = scan.nextInt();
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
8
Output:
Result:
Thus the above program was successfully executed and the output was
verified.
9
EX.NO:1(d) INSERTION SORT
DATE:
Aim:
Algorithm:
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
Step 5.1: Else,Shift greater elements in the array towards the right.
Program:
import java.util.Scanner;
int n, i, j, element;
10
System.out.print("Enter the Size of elements: ");
n = scan.nextInt();
arr[i] = scan.nextInt();
element = arr[i];
arr[j+1] = arr[j];
arr[j+1] = element;
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:
Algorithm:
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]);
Do
15
{
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");
switch(in.nextInt())
case 1:
s.push(in.nextInt());
break;
case 2:
break;
case 3:
break;
16
break;
case 5: System.exit(0);
break;
break;
}while(in.nextInt()==1);
int n, i, j, element;
n = scan.nextInt();
arr[i] = scan.nextInt();
17
element = arr[i];
arr[j+1] = arr[j];
arr[j+1] = element;
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:
Program:
import java.io.*;
class QueueAction {
int items[];
void getdata() {
try {
20
System.out.println("Enter the Limit :");
noOfItems = Integer.parseInt(is.readLine());
} catch (Exception e) {
System.out.println(e.getMessage());
void enqueue() {
try {
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) {
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 {
22
}
class QueueProgram {
int choice;
queue.getdata();
System.out.println("Queue\n\n");
try {
do {
System.out.println("1.Enqueue\n2.Dequeue\n3.Display\n4.Exit\n");
choice = Integer.parseInt(get.readLine());
switch (choice) {
case 1:
queue.enqueue();
break;
case 2:
queue.dequeue();
break;
case 3:
23
queue.display();
break;
} 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:
Algorithm:
Step 4: Get the user details [Name, ID, Address, Mail ID and Mobile
Step 5.2: If user enters -1 assume basic pay as 30000 and goto step 15 .
Step 7: Get the user details [Name, ID, Address, Mail ID and Mobile
Step 8.2: If user enters -1 assume basic pay as 25000 and goto step 15 .
26
Step 9: If user selects Associate Professor step 10.
Get the user details [Name, ID, Address, Mail ID and Mobile
Step 11.2 : If user enters -1 assume basic pay as 40000 and goto step 15 .
Step 13: Get the user details [Name, ID, Address, Mail ID and Mobile
Step 14.2:If user enters -1 assume basic pay as 70000 and goto step 15 .
no_of_days_in_the_current_month.
Step 16: Get the number of days worked from user that include Cl, WH, FH
DA = (Current_Basic_Pay/100) * 97.
27
PF = (Current_Basic_Pay/100) * 0.1.
Step 20: Display Payment Details [Name, ID, Address, Mail ID, Mobile
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 net_pay;
int no_of_days_in_current_month;
int no_of_days_worked;
28
Calendar cal;
Scanner input;
Employee()
no_of_days_in_current_month =
cal.getActualMaximum(Calendar.DAY_OF_MONTH);
getUserBasicDetails();
29
System.out.println("Mobile No: " + this.emp_mobile_no);
System.out.println("\nEarnings");
System.out.println("--------");
System.out.println("\nDeductions");
System.out.println("----------");
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();
this.no_of_days_worked = input.nextInt();
System.out.println("Programmer");
System.out.println("----------");
generatePaySlip();
else {
31
input.close();
System.exit(0);
public Programmer()
super();
computeProgrammerPay();
this.basic_pay = input.nextInt();
if (this.basic_pay == -1)
this.basic_pay = 30000;
computeCurrentBasicPay("Programmer");
generatePaySlip();
displayPaySlip();
32
}
public AssistantProfessor()
super();
computeAssistantProfessorPay();
this.basic_pay = input.nextInt();
if (this.basic_pay == -1) {
this.basic_pay = 25000;
computeCurrentBasicPay("AssistantProfessor");
generatePaySlip();
displayPaySlip();
33
public AssociateProfessor()
super();
computeAssociateProfessorPay();
this.basic_pay = input.nextInt();
if (this.basic_pay == -1) {
this.basic_pay = 40000;
computeCurrentBasicPay("AssociateProfessor");
generatePaySlip();
displayPaySlip();
public Professor() {
super();
computeProfessorPay();
34
public void computeProfessorPay()
this.basic_pay = input.nextInt();
if (this.basic_pay == -1) {
this.basic_pay = 70000;
computeCurrentBasicPay("Professor");
generatePaySlip();
displayPaySlip();
Programmer aProgrammer;
AssistantProfessor aAssistantProfessor;
AssociateProfessor aAssociateProfessor;
Professor aProfessor;
String choice;
int n_choice = 0;
35
while (n_choice != 5) {
System.out.println("***********************\n");
n_choice = Integer.parseInt(choice);
switch (n_choice) {
case 1:
System.out.println("Programmer Selected");
break;
case 2:
System.out.println("AssistantProfessor Selected");
break;
case 3:
System.out.println("AssociateProfessor Selected");
break;
case 4:
System.out.println("Professor Selected");
case 5:
36
userInput.close();
break;
default:
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:
Algorithm:
Step 3.1: Get the Length and Breath from the user.
Step 4.1: Get the Length and Height from the user.
40
Program:
import java.util.Scanner;
System.out.println("\nRectangle");
System.out.println("---------\n");
this.length = input.nextDouble();
41
System.out.println("\nTriangle");
System.out.println("---------\n");
this.length = input.nextDouble();
System.out.println("\nCircle");
System.out.println("-------\n");
this.length = input.nextDouble();
class area1
42
{
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:
rt.printArea();
break;
case 2:
tr.printArea();
break;
43
case 3:
cr.printArea();
break;
case 4:
userInput.close();
break;
default:
break;
44
Output:
45
Result:
Thus the above program was successfully executed and the output was
verified.
46
EX.NO:5 INTERFACE
DATE:
Aim:
Algorithm:
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.
Program:
import java.util.*;
interface Area2
double pi=3.14;
47
double calc(double x,double y);
return x*y;
return 0.5*x*y;
return pi*x*y;
48
public class interface1
int choice = 0;
do
System.out.println("\n1.retangle\n2.triangle\n3.circle\n4.exit");
choice = in.nextInt();
switch(choice)
double len=in.nextDouble();
double bread=in.nextDouble();
break;
double b=in.nextDouble();
49
System.out.println("enter the height of triangle");
double h=in.nextDouble();
double rad=in.nextDouble();
break;
case 4:System.out.println("thankyou!!!");
in.close();
break;
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:
Algorithm:
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’.
Program:
import java.util.Scanner;
run(cont);
54
Scanner scan = new Scanner(System.in);
while( cont.equalsIgnoreCase("y")) {
try {
System.out.println( marks);
catch(IllegalArgumentException i) {
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 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
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
Step 4.3: Else detect amount from balance and goto step 2.
57
Step 4.4: Prompt user with “enter the valid debit amount”.
Number,Current balance].
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:
Algorithm:
Step 3.1: If number is even then create and start thread that computes
Square of a number.
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.
Program:
import java.util.*;
int value;
64
while(true){
try{
this.sleep(1000);
}catch(InterruptedException e){}
value = num.nextInt(1000);
if(value%2==0){
new SquareGenThread(value).start();
else{
new CubeGenThread(value).start();
int number,square;
this.number = number;
try{
65
this.sleep(3000);
}catch(InterruptedException e){}
this.square = this.number*this.number;
int number,square;
this.number = number;
try{
this.sleep(2000);
}catch(InterruptedException e){}
this.square = this.number*this.number*this.number;
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:
Read,Write).
Algorithm:
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
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
Program:
68
{
String result = f.exists() ? " exists." : " does not exist."; System.out.println("\nThe
given file " +fName + result);
else if (fName.endsWith(".pdf"))
69
else if (fName.endsWith(".txt"))
else
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:
Algorithm:
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.
Program:
package genclass;
import java.util.*;
import java.io.*;
73
class Arr<T>{
public ArrayList<T>obj;
obj=new ArrayList<T>(size);
obj.add(index,item);
System.out.print(" "+obj);
return obj.remove(index);
int[] iArray={1,2,3,4,5};
Arr<Integer>iobj=new Arr<Integer>(10);
int i,index;
for(i=0;i<5;i++){
iobj.insert(i,iArray[i]);
74
}
iobj.display();
int item=sc.nextInt();
index=sc.nextInt();
iobj.insert(index,item);
iobj.display();
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);
for(i=0;i<5;i++){
dobj.insert(i,dArray[i]);
dobj.display();
75
double ditem=sc.nextDouble();
index=sc.nextInt();
dobj.insert(index,ditem);
dobj.display();
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:
Algorithm:
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.
78
Program:
package genmeth;
class gen{
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);
79
Integer a[]={34,56,78,67,11};
s.bubblesortg(a);
Double d[]={3.4,54.6,78.9,12.4,2.4};
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 2: Create a array of number and array of strings and pass it to generic
function
Step 3.3: If it is greater than MAX then store current element as MAX
Step 3.5: Goto step 3.1 until all the elements has been processed.
Step 4.3: If it is greater than MAX then store current element as MAX
82
Step 4.5: Goto step 3.1 until all the elements has been processed.
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:
Algorithm:
Step 7: Create a Button Group such that it contains three radio buttons Red,
Yellow, Green
Step 8: Also create a sample Traffic signal demo using rectangle and ovals
using 2D graphics
85
Program:
/*
*/
package javafxapplication4;
import javafx.application.Application;
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
*/
87
Label l5=new Label("Enter the Type of Connection(Com/Dom):");
@Override
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());
primaryStage.setScene(scene);
primaryStage.show();
88
}
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()));
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
}
launch(args);
double conno;
String conname;
double preread;
double currentread;
this.currentread=currentread;
this.preread=preread;
this.conname=name;
this.conno=cno;
90
return currentread;
return preread;
return conname;
return conno;
double bill;
double currentreading=currentread-preread;
bill =currentreading*1;
bill =(100*1)+((currentreading-100)*2.50);
bill =(100*1)+(100*2.50)+((currentreading-200)*4);
else
bill=(100*1)+(100*2.50)+(300*4)+((currentreading-500)*6);
91
return bill;
double bill;
double currentreading=currentread-preread;
bill =currentreading*2;
bill =(100*2)+((currentreading-100)*4.50);
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:
Algorithm:
Step 3: Insert the fields into the employee table with the following fields: name,
rollno, course, subject, marks.
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:
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 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.1 Get the Text View content as Operant 1 and Set the display to null.
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.
97
Step 5.4: If operator is “multiply” then display Text View as Operant 1 *
Operant
Step 6.1: Change Operant Types [+,-,x,/ into sin, cos, tan, log] and goto step
2
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 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