0% found this document useful (0 votes)
15 views

OOPS FULL LAB MANUAL-01

Uploaded by

santhikala
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

OOPS FULL LAB MANUAL-01

Uploaded by

santhikala
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 43

1.

Solve problems by using sequential search, binary


search, and quadratic sorting algorithms (selection,
insertion)
Program
A.Sequential search
public class ArraySearcher
{/** Finds the index of a value in an array of integers.
* @param elements an array containing the items to be
searched.
* @param target the item to be found in elements.
* @return an index of target in elements if found; -1
otherwise.
*/
public static int sequentialSearch(int[] elements, int
target)
{
for (int j = 0; j < elements.length; j++)
{
if (elements[j] == target)
{
return j;
}
}
return -1;
}

public static void main(String[] args)


{
int[] numArray = {3, -2, 9, 38, -23};
System.out.println("Tests of sequentialSearch");
System.out.println(sequentialSearch(numArray,3));
System.out.println(sequentialSearch(numArray,9));
System.out.println(sequentialSearch(numArray,-23));
System.out.println(sequentialSearch(numArray,99));
}

Output:
Tests of sequentialSearch
0
2
4
-1

B.Binary search
public class SearchTest
{
public static int binarySearch(int[] elements, int target)
{
int left = 0;
int right = elements.length - 1;
while (left <= right)
{
int middle = (left + right) / 2;
if (target < elements[middle])
{
right = middle - 1;
}
else if (target > elements[middle])
{
left = middle + 1;
}
else {
return middle;
}
}
return -1;
}

public static void main(String[] args)


{
int[] arr1 = {-20, 3, 15, 81, 432};

// test when the target is in the middle


int index = binarySearch(arr1,15);
System.out.println(index);
// test when the target is the first item in the array
index = binarySearch(arr1,-20);
System.out.println(index);
// test when the target is in the array - last
index = binarySearch(arr1,432);
System.out.println(index);
// test when the target is not in the array
index = binarySearch(arr1,53);
System.out.println(index);
}
}

Output:
2
0
4
-1

2.Develop stack and queue data structures using classes


and objects.

Program
A.Stack
\// Stack implementation in Java
class Stack {
// store elements of stack
private int arr[];
// represent top of stack
private int top;
// total capacity of the stack
private int capacity;
// Creating a stack
Stack(int size) {
// initialize the array
// initialize the stack variables
arr = new int[size];
capacity = size;
top = -1;
}
// push elements to the top of stack
public void push(int x) {
if (isFull()) {
System.out.println("Stack OverFlow");
// terminates the program
System.exit(1);
}
// insert element on top of stack
System.out.println("Inserting " + x);
arr[++top] = x;
}
// pop elements from top of stack
public int pop() {
// if stack is empty
// no element to pop
if (isEmpty()) {
System.out.println("STACK EMPTY");
// terminates the program
System.exit(1);
}
// pop element from top of stack
return arr[top--];
}
// return size of the stack
public int getSize() {
return top + 1;
}
// check if the stack is empty
public Boolean isEmpty() {
return top == -1;
}
// check if the stack is full
public Boolean isFull() {
return top == capacity - 1;
}
// display elements of stack
public void printStack() {
for (int i = 0; i <= top; i++) {
System.out.print(arr[i] + ", ");
}
}
public static void main(String[] args) {
Stack stack = new Stack(5);
stack.push(1);
stack.push(2);
stack.push(3);
System.out.print("Stack: ");
stack.printStack();
// remove element from stack
stack.pop();
System.out.println("\nAfter popping out");
stack.printStack();
}
}
Output
Inserting 1
Inserting 2
Inserting 3
Stack: 1, 2, 3,
After popping out
1, 2,

B.QUEUE

import java.util.*;
public class Main {
public static void main(String[] args) {
Queue<Integer> q1 = new
LinkedList<Integer>();
//Add elements to the Queue
q1.add(10);
q1.add(20);
q1.add(30);
q1.add(40);
q1.add(50);
System.out.println("Elements in
Queue:"+q1);
//remove () method =>removes first
element from the queue
System.out.println("Element
removed from the queue: "+q1.remove());
//element() => returns head of the
queue
System.out.println("Head of the
queue: "+q1.element());
//poll () => removes and returns the
head
System.out.println("Poll():Returned
Head of the queue: "+q1.poll());
//returns head of the queue
System.out.println("peek():Head of
the queue: "+q1.peek());
//print the contents of the Queue
System.out.println("Final
Queue:"+q1);
}
}
Output:
Elements in Queue:[10, 20, 30, 40, 50]
Element removed from the queue: 10
Head of the queue: 20
Poll():Returned Head of the queue: 20
peek():Head of the queue: 30
Final Queue:[30, 40, 50]

.3..Develop a java application with an 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. Add Basic Pay
(BP) as the member of all the inherited classes with
97% of BP as DA, 10 % of BP as HRA, 12% of BP as
PF, 0.1% of BP for staff club funds. Generate pay slips
for the employees with their gross and net salary.

Program:
import java.util.*;
class employee
{
int empid;
long mobile;
String name, address, mailid;
Scanner get = new Scanner(System.in);
void getdata()
{
System.out.println("Enter Name of the Employee");
name = get.nextLine();
System.out.println("Enter Mail id");
mailid = get.nextLine();
System.out.println("Enter Address of the
Employee:");
address = get.nextLine();
System.out.println("Enter employee id ");
empid = get.nextInt();
System.out.println("Enter Mobile Number");
mobile = get.nextLong();
}
void display()
{
System.out.println("Employee Name: "+name);
System.out.println("Employee id : "+empid);
System.out.println("Mail id : "+mailid);
System.out.println("Address: "+address);
System.out.println("Mobile Number: "+mobile);
19
}
}
class programmer extends employee
{
double salary,bp,da,hra,pf,club,net,gross;
void getprogrammer()
{
System.out.println("Enter basic pay");
bp = get.nextDouble();
}
void calculateprog()
{
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
System.out.println("**************************
**********************");
System.out.println("PAY SLIP FOR
PROGRAMMER");
System.out.println("**************************
**********************");
System.out.println("Basic Pay:Rs"+bp);
System.out.println("DA:Rs"+da);
System.out.println("PF:Rs"+pf);
System.out.println("HRA:Rs"+hra);
System.out.println("CLUB:Rs"+club);
System.out.println("GROSS PAY:Rs"+gross);
20
System.out.println("NET PAY:Rs"+net);
}
}
class asstprofessor extends employee
{
double salary,bp,da,hra,pf,club,net,gross;
void getasst()
{
System.out.println("Enter basic pay");
bp = get.nextDouble();
}
void calculateasst()
{
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
System.out.println("**************************
**********************");
System.out.println("PAY SLIP FOR ASSISTANT
PROFESSOR");
System.out.println("**************************
**********************");
System.out.println("Basic Pay:Rs"+bp);
System.out.println("DA:Rs"+da);
System.out.println("HRA:Rs"+hra);
Syste m.out.println("PF:Rs"+pf);
Syste m.out.println("CLUB:Rs"+club);
21
System.out.println("GROSS PAY:Rs"+gross);
System.out.println("NET PAY:Rs"+net);
}
}
class associateprofessor extends employee
{
double salary,bp,da,hra,pf,club,net,gross;
void getassociate()
{
System.out.println("Enter basic pay");
bp = get.nextDouble();
}
void calculateassociate()
{
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
System.out.println("**************************
**********************");
System.out.println("PAY SLIP FOR ASSOCIATE
PROFESSOR");
System.out.println("**************************
**********************");
System.out.println("Basic Pay:Rs"+bp);
System.out.println("DA:Rs"+da);
System.out.println("HRA:Rs"+hra);
System.out.println("PF:Rs"+pf);
22
System.out.println("CLUB:Rs"+club);
System.out.println("GROSS PAY:Rs"+gross);
System.out.println("NET PAY:Rs"+net);
}
}
class professor extends employee
{
double salary,bp,da,hra,pf,club,net,gross;
void getprofessor()
{
Syste m.out.println("Enter basic pay");
bp = get.nextDouble();
}
void calculateprofessor()
{
da=(0. 97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
System.out.println("**************************
**********************");
System.out.println("PAY SLIP FOR PROFESSOR");
System.out.println("**************************
**********************");
System.out.println("Basic Pay:Rs"+bp);
System.out.println("DA:Rs"+da);
System.out.println("HRA:Rs"+hra);
System.out.println("PF:Rs"+pf);
System.out.println("CLUB:Rs"+club);
System.out.println("GROSS PAY:Rs"+gross);
System.out.println("NET PAY:Rs"+net);
}
}
class salary
{
public static void main(String args[])
{
int choice,cont;
do
{
System.out.println("PAYROLL");
System.out.println(" 1.PROGRAMMER \t
2.ASSISTANT PROFESSOR \t 3.ASSOCIATE
PROFESSOR \t 4.PROFESSOR ");
Scann er c = new Scanner(System.in);
choice=c.nextInt();
switch(choice)
{
case 1:
{
programmer p=new programmer();
p.getdata();
p.getprogrammer();
p.display();
p.calculateprog();
break;
}
case 2:
{
asstprofessor asst=new asstprofessor();
asst.getdata();
asst.getasst();
asst.display();
asst.calculateasst();
break;
}
case 3:
{
associateprofessor asso=new associateprofessor();
asso.g etdata();
asso.getassociate();
asso.display();
asso.calculateassociate();
break;
}
case 4:
{
professor prof=new professor();
profg etdata();
profgetprofessor();
prof.display();
prof.calculateprofessor();
break;
}
}
System.out.println("Do u want to continue 0 to quit
and 1 to continue ");
cont=c.nextInt();
}while(cont==1);
}
}

Output:
4.Write a Java Program to create an abstract class
named Shape that contains two integers and an
empty method named printArea(). Provide three
classes named Rectangle, Triangle and Circle such
that each one of the classes extends the class
Shape. Each one of the classes contains only the
method printArea( ) that prints the area of the
given shape.
Program:
import java.util.*;
abstract class Shapes
{
double a,b;
abstract void printArea();
}
class Rectangle extends Shapes
{
void printArea()
{
System. out.println("\t\tCalculating Area of
Rectangle");
Scanner input=new Scanner(System.in);
System.out.println("Enter length:");
a=input.nextDouble();
System.out.println("\nEnter breadth:");
b=input.nextDouble();
double area=a*b;
System.out.println("Area of Rectangle:"+area);
}
}
class Triangle extends Shapes
{
void printArea()
{
System.out.println("\t\tCalculating Area of
Triangle");
Scanner input=new Scanner(System.in);
System.out.println("Enter height:");
a=input.nextDouble();
System.out.println("\nEnter breadth:");
b=input.nextDouble();
double area=0.5*a*b;
System.out.println("Area of Triangle:" +area);
}
}
class Circle extends Shapes
{
void printArea()
{
System.out.println("\t\tCalculating Area of
Circle");
Scanner input=new Scanner(System.in);
System.out.println("Enter radius:");
a=input.nextDouble();
double area=3.14*a*a;
System.out.println("Area of Circle:" +area);
}
}
class AbstractClassDemo
{
public static void main(String[] args)
{
Shapes obj;
obj=new Rectangle();
obj.printArea();
obj=ne w Triangle();
obj.printArea();
obj=new Circle();
obj.printArea();
}
}
Output:

5. Using Interface
import java.util.Scanner;

interface S{
public void rectangle();
public void triangle();
public void circle();
}
class a implements S{

@Override
public void rectangle()
{
System.out.println("\t\tCalculating Area of
Rectangle");
Scanner input=new Scanner(System.in);
System.out.println("Enter length:");
double a = input.nextDouble();
System.out.println("\nEnter breadth:");
double b=input.nextDouble();
double area=a*b;
System.out.println("Area of Rectangle:"+area);
}

@Override
public void triangle()
{
System.out.println("\t\tCalculating Area of
Triangle");
Scanner input=new Scanner(System.in);
System.out.println("Enter height:");
double a = input.nextDouble();
System.out.println("\nEnter breadth:");
double b=input.nextDouble();
double area=0.5*a*b;
System.out.println("Area of Triangle:" +area);
}
public void circle()
{
System.out.println("\t\tCalculating Area of
Circle");
Scanner input=new Scanner(System.in);
System.out.println("Enter radius:");
double a = input.nextDouble();
double area=3.14*a*a;
System.out.println("Area of Circle:" +area);
}
}
public class inter {
public static void main(String[] args) {
a p=new a() ;
p.rectangle();
p.triangle();
p.circle();
}
}

6.Implement exception handling and creation of user


defined exceptions

Program:
import java.util.Scanner;
45
class NegativeAmtException extends Exception
{
String msg;
NegativeAmtException(String msg)
{
this.msg=msg;
}
public String toString()
{
return msg;
}
}
public class userdefined
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter Amount:");
int a=s.nextInt();
try
{
if(a<0)
{
throw new NegativeAmtException("Invalid Amount");
}
System.out.println("Amount Deposited");
}
46
catch(NegativeAmtException e)
{
System.out.println(e);
}
}
}
OUTPUT
(b) PROGRAM
class MyException extends Exception{
47
String str1;
MyException(String str2)
{
str1=str2;
}
public String toString()
{
return ("MyException Occurred: "+str1) ;
}
}
class example
{
public static void main(String args[])
{
try
{
System.out.println("Starting of try block");
throw new MyException("This is My error Message");
}
catch(MyException exp)
{
System.out.println("Catch Block") ;
System.out.println(exp) ;
}
}}
OUTPUT:

7.Write a java program that implements a multi-


threaded application that has three threads. First
thread generates a random integer every 1 second and
if the value is even, the second thread computes the
square of the number and prints. If the value is odd,
the third thread will print the value of the cube of the
number.
Program:
import java.util.*;
54
class even implements Runnable
{
public int x;
public even(int x)
{
this.x = x;
}
public void run()
{
System.out.println("New Thread "+ x +" is EVEN and
Square of " + x + " is: " + x * x);
}
}
class odd implements Runnable
{
public int x;
public odd(int x)
{
this.x = x;
}
public void run()
{
System.out.println("New Thread "+ x +" is ODD and
Cube of " + x + " is: " + x * x * x);
}
}
class A extends Thread
{
public void run()
55
{
int num = 0;
Random r = new Random();
try
{
for (int i = 0; i < 5; i++)
{
num = r.nextInt(100);
System.out.println("Main Thread and Generated Number
is " + num);
if (num % 2 == 0)
{
Thread t1 = new Thread(new even(num));
t1.start();
}
else
{
Thread t2 = new Thread(new odd(num));
t2.start();
}
Thread.sleep(1000);
System.out.println("--------------------------------------");
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
56
}
}
public class multithreadprog
{
public static void main(String[] args)
{
A a = new A();
a.start();
}
}
Output:

8.File operations

import java.io.FileWriter;
import java.io.IOException;

class GFG {
public static void main(String[] args)
{

// File name specified


File obj = new File("myfile.txt");
System.out.println("File Created!");
try {
File Obj = new File("myfile.txt");
if (Obj.createNewFile()) {
System.out.println("File created: "
+ Obj.getName());
}
else {
System.out.println("File already exists.");
}
}
catch (IOException e) {
System.out.println("An error has occurred.");
e.printStackTrace();
}
try {
File Obj = new File("myfile.txt");
Scanner Reader = new Scanner(Obj);
while (Reader.hasNextLine()) {
String data = Reader.nextLine();
System.out.println(data);
}
Reader.close();
}
catch (FileNotFoundException e) {
System.out.println("An error has occurred.");
e.printStackTrace();
}
try {
FileWriter Writer
= new FileWriter("myfile.txt");
Writer.write(
"Files in Java are seriously good!!");
Writer.close();
System.out.println("Successfully written.");
}
catch (IOException e) {
System.out.println("An error has occurred.");
e.printStackTrace();
}
File Obj = new File("myfile.txt");
if (Obj.delete()) {
System.out.println("The deleted file is : "
+ Obj.getName());
}
else {
System.out.println(
"Failed in deleting the file.");
}
}
}
output:
File Created!
File created: myfile.txt
Successfully written.
The deleted file is : myfile.txt

9.Develop applications to demonstrate the features of


generics classes.
Program:
class MyClass<T extends Comparable<T>>
{
T[] vals;
MyClass(T[] o)
{
vals = o;
}
public T min()
{
T v = vals[0];
for(int i=1; i < vals.length; i++)
if(vals[i].compareTo(v) < 0)
v = vals[i];
return v;
}
public T max()
{
T v = vals[0];
for(int i=1; i < vals.length;i++)
if(vals[i].compareTo(v) > 0)
v = vals[i];
return v;
}
}
class gendemo
{
public static void main(String args[])
60
{
int i;
Integer inums[]={10,2,5,4,6,1};
Character chs[]={'v','p','s','a','n','h'};
Double d[]={20.2,45.4,71.6,88.3,54.6,10.4};
MyClass<Integer> iob = new MyClass<Integer>(inums);
MyClass<Character> cob = new
MyClass<Character>(chs);
MyClass<Double>dob = new MyClass<Double>(d);
System.out.println("Max value in inums: " + iob.max());
System.out.println("Min value in inums: " + iob.min());
System.out.println("Max value in chs: " + cob.max());
System.out.println("Min value in chs: " + cob.min());
System.out.println("Max value in chs: " + dob.max());
System.out.println("Min value in chs: " + dob.min());
}
}

Output:
10. Develop application using javaFX control, layouts
and menus
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");
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,E
ditMenu3);
root.setTop(menubar);
FileMenu.getItems().addAll(filemenu1,filemenu2,filem
enu3);
menubar.getMenus().addAll(FileMenu,EditMenu);
primaryStage.setScene(scene);
primaryStage.show();

}
}

11.Develop a mini project for any application using


Java concepts
Program:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
public class calci extends JFrame implements
ActionListener
{
Container contentpane;
JPanel DisplayPanel,ControlPanel;
JTextField txt;
JButton
one,two,three,four,five,six,seven,eight,nine,zero;
JButton plus,min,mul,div,log,CLR,exp;
JButton
eq,addSub,dot,memread,memcancel,memplus;
JButton sqrt,sin,cos,tan,onebyx;
double tempnum,tempnextnum,result,ans;
static double ValueInMem;
int num1=0,num2=0;
int MemPlusFlag=1,RepeatFlag=0;
char ch;
calci()
{
contentpane=getContentPane();
contentpane.setLayout(new BorderLayout());
JPanel DisplayPanel=new JPanel();
txt=new JTextField(30);
txt.setHorizontalAlignment(SwingConstants.RIGHT);
txt.addKeyListener(
new KeyAdapter()
{
public void keyTyped(KeyEvent keyevent)
{
char ch=keyevent.getKeyChar();
if(ch>='0'&&ch<='9')
{
}
else
{
keyevent.consume();
}
}
});
DisplayPanel.add(txt);
ControlPanel=new JPanel();
contentpane.add("Center",ControlPanel);
contentpane.add("North",DisplayPanel);
ControlPanel.setLayout(new GridLayout(7,4,5,5));
memcancel=new JButton("MC");
ControlPanel.add(memcancel);
memcancel.addActionListener(this);
one=new JButton("1");
ControlPanel.add(one);
one.addActionListener(this);
two=new JButton("2");
ControlPanel.add(two);
two.addActionListener(this);
three=new JButton("3");
ControlPanel.add(three);
three.addActionListener(this);
memread=new JButton("MR");
ControlPanel.add(memread);
memread.addActionListener(this);
four=new JButton("4");
ControlPanel.add(four);
four.addActionListener(this);
five=new JButton("5");
ControlPanel.add(five);
five.addActionListener(this);
six=new JButton("6");
ControlPanel.add(six);
six.addActionListener(this);
memplus=new JButton("M+");
ControlPanel.add(memplus);
memplus.addActionListener(this);
seven=new JButton("7");
ControlPanel.add(seven);
seven.addActionListener(this);
eight=new JButton("8");
ControlPanel.add(eight);
eight.addActionListener(this);
nine=new JButton("9");
ControlPanel.add(nine);
nine.addActionListener(this);
zero=new JButton("0");
ControlPanel.add(zero);
zero.addActionListener(this);
addSub=new JButton("+/-");
ControlPanel.add(addSub);
addSub.addActionListener(this);
dot=new JButton(".");
ControlPanel.add(dot);
dot.addActionListener(this);
eq=new JButton("=");
ControlPanel.add(eq);
eq.addActionListener(this);
plus=new JButton("+");
ControlPanel.add(plus);
plus.addActionListener(this);
min=new JButton("-");
ControlPanel.add(min);
min.addActionListener(this);
mul=new JButton("*");
ControlPanel.add(mul);
mul.addActionListener(this);
div=new JButton("/");
ControlPanel.add(div);
div.addActionListener(this);
sqrt=new JButton("SQRT");
ControlPanel.add(sqrt);
sqrt.addActionListener(this);
log=new JButton("LOG");
ControlPanel.add(log);
log.addActionListener(this);
sin=new JButton("SIN");
ControlPanel.add(sin);
sin.addActionListener(this);
cos=new JButton("COS");
ControlPanel.add(cos);
cos.addActionListener(this);
tan=new JButton("TAN");
ControlPanel.add(tan);
tan.addActionListener(this);
exp=new JButton("Exp");
ControlPanel.add(exp);
exp.addActionListener(this);
onebyx=new JButton("1/x");
ControlPanel.add(onebyx);
onebyx.addActionListener(this);
CLR=new JButton("AC");
ControlPanel.add(CLR);
CLR.addActionListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE
);
}
public void actionPerformed(ActionEvent e)
{
String s=e.getActionCommand();
if(s.equals("1"))
{
if(RepeatFlag==0)
{
txt.setText(txt.getText()+"1");
}
else
{
txt.setText("");
txt.setText(txt.getText()+"1");
RepeatFlag=0;
}
}
if(s.equals("2"))
{
if(RepeatFlag==0)
{
txt.setText(txt.getText()+"2");
}
else
{
txt.setText("");
txt.setText(txt.getText()+"2");
RepeatFlag=0;
}
}
if(s.equals("3"))
{
if(RepeatFlag==0)
{
txt.setText(txt.getText()+"3");
}
else
{
txt.setText("");
txt.setText(txt.getText()+"3");
RepeatFlag=0;
}
}
if(s.equals("4"))
{
if(RepeatFlag==0)
{
txt.setText(txt.getText()+"4");
}
else
{
txt.setText("");
txt.setText(txt.getText()+"4");
RepeatFlag=0;
}
}
if(s.equals("5"))
{
if(RepeatFlag==0)
{
txt.setText(txt.getText()+"5");
}
else
{
txt.setText("");
txt.setText(txt.getText()+"5");
RepeatFlag=0;
}
}
if(s.equals("6"))
{
if(RepeatFlag==0)
{
txt.setText(txt.getText()+"6");
}
else
{
txt.setText("");
txt.setText(txt.getText()+"6");
RepeatFlag=0;
}
}
if(s.equals("7"))
{
if(RepeatFlag==0)
{
txt.setText(txt.getText()+"7");
}
else
{
txt.setText("");
txt.setText(txt.getText()+"7");
RepeatFlag=0;
}
}
if(s.equals("8"))
{
if(RepeatFlag==0)
{
txt.setText(txt.getText()+"8");
}
else
{
txt.setText("");
txt.setText(txt.getText()+"8");
RepeatFlag=0;
}
}
if(s.equals("9"))
{
if(RepeatFlag==0)
{
txt.setText(txt.getText()+"9");
}
else
{
txt.setText("");
txt.setText(txt.getText()+"9");
RepeatFlag=0;
}
}
if(s.equals("0"))
{
if(RepeatFlag==0)
{
txt.setText(txt.getText()+"0");
}
else
{
txt.setText("");
txt.setText(txt.getText()+"0");
RepeatFlag=0;
}
}
if(s.equals("AC"))
{
txt.setText("");
num1=0;
num2=0;
RepeatFlag=0;
}
if(s.equals("+/-"))
{
if(num1==0)
{
txt.setText("-"+txt.getText());
num1=1;
}
else
{
txt.setText(txt.getText());
}
}
if(s.equals("."))
{
if(num2==0)
{
txt.setText(txt.getText()+".");
num2=1;
}
else
{
txt.setText(txt.getText());
}
}
if(s.equals("+"))
{
if(txt.getText().equals(""))
{
txt.setText("");
tempnum=0;
ch='+';
}
else
{
tempnum=Double.parseDouble(txt.getText());
txt.setText("");
ch='+';
num2=0;
num1=0;
}
txt.requestFocus();
}
if(s.equals("-"))
{
if(txt.getText().equals(""))
{
txt.setText("");
tempnum=0;
ch='-';
}
else
{
num1=0;
num2=0;
tempnum=Double.parseDouble(txt.getText());
txt.setText("");
ch='-';
}
txt.requestFocus();
}
if(s.equals("/"))
{
if(txt.getText().equals(""))
{
txt.setText("");
tempnum=1;
ch='/';
}
else
{
num1=0;
num2=0;
tempnum=Double.parseDouble(txt.getText());
ch='/';
txt.setText("");
}
txt.requestFocus();
}
if(s.equals("*"))
{
if(txt.getText().equals(""))
{
txt.setText("");
tempnum=1;
ch='*';
}
else
{
num1=0;
num2=0;
tempnum=Double.parseDouble(txt.getText());
ch='*';
txt.setText("");
}
txt.requestFocus();
}
if(s.equals("MC"))
{
ValueInMem=0;
txt.setText("");
txt.setText(txt.getText()+ValueInMem);
}
if(s.equals("M+"))
{
if(MemPlusFlag==1)
{
ValueInMem=Double.parseDouble(txt.getText());
MemPlusFlag++;
}
else
{
ValueInMem+=Double.parseDouble(txt.getText());
txt.setText(""+ValueInMem);
}
}
if(s.equals("LOG"))
{
if(txt.getText().equals(""))
{
txt.setText("");
}
else
{
ans=Math.log(Double.parseDouble(txt.getText()));
txt.setText("");
txt.setText(txt.getText()+ans);
}
}
if(s.equals("1/x"))
{
if(txt.getText().equals(""))
{
txt.setText("");
}
else
{
ans=1/Double.parseDouble(txt.getText());
txt.setText("");
txt.setText(txt.getText()+ans);
}
}
if(s.equals("Exp"))
{
if(txt.getText().equals(""))
{
txt.setText("");
}
else
{
ans=Math.exp(Double.parseDouble(txt.getText()));
txt.setText("");
txt.setText(txt.getText()+ans);
}
}
if(s.equals("Sqrt"))
{
if(txt.getText().equals(""))
{
txt.setText("");
}
else
{
ans=Math.sqrt(Double.parseDouble(txt.getText()));
txt.setText("");
txt.setText(txt.getText()+ans);
}
}
if(s.equals("SIN"))
{
if(txt.getText().equals(""))
{
txt.setText("");
}
else
{
ans=Math.sin(Double.parseDouble(txt.getText()));
txt.setText("");
txt.setText(txt.getText()+ans);
}
}
if(s.equals("COS"))
{
if(txt.getText().equals(""))
{
txt.setText("");
}
else
{
ans=Math.cos(Double.parseDouble(txt.getText()));
txt.setText("");
txt.setText(txt.getText()+ans);
}
}
if(s.equals("TAN"))
{
if(txt.getText().equals(""))
{
txt.setText("");
}
else
{
ans=Math.tan(Double.parseDouble(txt.getText()));
txt.setText("");
txt.setText(txt.getText()+ans);
}
}
if(s.equals("="))
{
if(txt.getText().equals(""))
{
txt.setText("");
}
else
{
tempnextnum=Double.parseDouble(txt.getText());
switch(ch)
{
case'+':
result=tempnum+tempnextnum;
break;
case'-':
result=tempnum-tempnextnum;
break;
case'/':
result=tempnum/tempnextnum;
break;
case'*':
result=tempnum*tempnextnum;
break;
}
txt.setText("");
txt.setText(txt.getText()+result);
RepeatFlag=1;
}
}
txt.requestFocus();
}
public static void main(String args[])
{
calci c=new calci();
c.setTitle("My Calculator");
c.pack();
c.setVisible(true);
}
}

Output:

You might also like