[go: up one dir, main page]

0% found this document useful (0 votes)
3 views42 pages

OOPS USING JAVA LAB (2023-24)

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 42

SRINIVAS UNIVERSITY

INSTITUTE OF ENGINEERING AND TECHNOLOGY


MUKKA, MANGALURU

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

LAB MANUAL
FOR
OOPS USING JAVA 2023-24
SUBJECT CODE: 22SCS033

PREPARED BY:
Mrs. SWATHI R , Assistant Professor

Name:_________________________________

SECTION/ Branch:______________________

Semester:_______________________________

USN:____________________________________
SRINIVAS UNIVERSITY
INSTITUTE OF ENGINEERING AND TECHNOLOGY
MUKKA, MANGALURU
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

III Semester B.Tech

OOPS USING JAVA LABORATORY


Sub Code 21SCSL37
TEACHING HOURS/ WEEK IA Marks 50
Lecture Tutorial Practical Exam Marks 50
01 00 02 Exam Hours 03
Credits : 2

List of Experiments:
Sr.No Experiment Details
1 Write a Java program that display the roots of a quadratic equation ax2+bx=0.
Calculate thediscriminate D and basing on value of D, describe the nature of root.

2 a. Write a Java program that works as a simple calculator.


b. Write a Java program to sort for an element in a given list of elements using
bubble sort.
3 Create a Java class called Student with the following details as variables within it.
USN, Name, Branch, Phone.
Write a Java program to create n Student objects and print the USN, Name,
Branch, and Phone of theseobjects with suitable headings.
4 a. Write a Java Program to define a class, define instance methods and overload
them and use them fordynamic method invocation.
b. Write a java program for abstract class to find areas of different shapes.

5 Design a superclass called Staff with details as StaffId, Name, Phone, Salary. Extend
this class by writing three subclasses namely Teaching (domain, publications),
Technical (skills), and Contract (period). Write a Java program to read and display at
least 3 staff objects of all three categories.

6 Write a Java class called Customer to store their name and date_of_birth. The
date_of_birth format should be dd/mm/yyyy. Write methods to read customer data as
<name, dd/mm/yyyy> and display as <name, dd, mm, yyyy> using StringTokenizer
class considering the delimiter character as “/”.

7 Write a Java program that implements a multi-thread application that has three
threads. First thread generates a random integer for every 1 second; second thread
computes the square of the number and prints; third thread will print the value of
cube of the number.

8 Write a java program that displays the number of characters, lines and words in a
text file.
9 Write a java program that reads a file and displays the file on the screen with line
number b.

10 Write a Java program that works as a simple calculator. Use a grid layout to arrange
buttons for the digits and for the +, -,*, % operations. Add a text field to display the
result. Handle any possible exceptions like divide by zero

COURSE OBJECTIVES:
 Design and implement various algorithms in JAVA.
 Employ various design strategies for problem solving constructs

COURSE OUTCOMES:
 Apply the knowledge of mathematics, science engineering fundamentals, and an
engineering Specialization to the solution of complex engineering problems.
 Understand the impact of the professional engineering solutions in societal and
environmental Contexts, and demonstrate the knowledge of, and need for sustainable
development

SCHEME OF EXAMINATION:
1. All laboratory experiments are to be included for practical examination.
2. Students are allowed to pick one experiment from the lot.
3. Strictly follow the instructions as printed on the cover page of answer script
4. Marks distribution: Procedure + Conduction + Viva:12 + 28 +10 = 50
5. Change of experiment is allowed only once and marks allotted to the procedure part to
be made zero
LABORATORY GUIDELINES

1. Equipment in the lab for the use of student community. Students need to maintain a
proper decorum in the computer lab. Students must use the equipment with care. Any
damage is caused is punishable.

2. Students are instructed to come to lab in formal dresses only.

3. Students are supposed to occupy the systems allotted to them and are not supposed to
talk or make noise in the lab.

4. Students are required to carry their observation book and lab records with completed
exercises while entering the lab.

5. Lab records need to be submitted every week.

6. Students are not supposed to use pen drives in the lab.

Do’s
1. Come with completed observation and record

2. Wear ID card before entering into the lab.

3. Write in time, out time and system details in the login register.

4. Remove your shoes or wear foot socks before you enter the lab.

5. Do not touch any part of the computer with wet hands.

6. Shut down the computer properly.

7. Read and understand how to carry out an activity thoroughly before coming to the
laboratory.

8. Report any broken plugs or exposed electrical wires to your lecturer/laboratory


technician immediately.

9. Be on time
Don’ts
1. Do not eat or drink in the laboratory.

2. Do not operate mobile phones in the lab.

3. Do not change system settings.

4. Do not disturb your neighboring students. They may be busy in completing tasks.

5. Do not remove anything from the computer laboratory without permission.

6. Do not use pen drives.


7. Do not misbehave.

8. Do not switch off the computer directly.

Serial no Experiments Page no


1 Write a Java program that display the roots of a quadratic 1-2
equation ax2+bx=0. Calculate thediscriminate D and basing on
value of D, describe the nature of root.
2 a. Write a Java program that works as a simple calculator. 3-5
b. Write a Java program to sort for an element in a given list 6-8
of elements using bubble sort.
3 Create a Java class called Student with the following details as 9-11
variables within it. USN, Name, Branch, Phone.
Write a Java program to create n Student objects and print the
USN, Name, Branch, and Phone of theseobjects with suitable
headings.
4 a. Write a Java Program to define a class, define instance 12
methods and overload them and use them fordynamic
method invocation.
b. Write a java program for abstract class to find areas of 13-14
different shapes.

5 Design a superclass called Staff with details as StaffId, Name, 15-18


Phone, Salary. Extend this class by writing three subclasses
namely Teaching (domain, publications), Technical (skills), and
Contract (period). Write a Java program to read and display at
least 3 staff objects of all three categories.
6 Write a Java class called Customer to store their name and 19-20
date_of_birth. The date_of_birth format should be dd/mm/yyyy.
Write methods to read customer data as <name, dd/mm/yyyy>
and display as <name, dd, mm, yyyy> using StringTokenizer
class considering the delimiter character as “/”.
7 Write a Java program that implements a multi-thread application 21-26
that has three threads. First thread generates a random integer for
every 1 second; second thread computes the square of the
number and prints; third thread will print the value of cube of the
number.
8 Write a java program that displays the number of characters, 27-28
lines and words in a text file.
9 Write a java program that reads a file and displays the file on the 29-31
screen with line number b.
10 Write a Java program that works as a simple calculator. Use a 32-34
grid layout to arrange buttons for the digits and for the +, -,*, %
operations. Add a text field to display the result. Handle any
possible exceptions like divide by zero
Experiments

1. Write a Java program that display the roots of a quadratic equation ax2+bx=0.
Calculate the discriminate D and basing on value of D, describe the nature of root.

public class Main

public static void main(String[] args)

// value a, b, and c

double a = 2.3, b = 4, c = 5.6;

double root1, root2;

// calculate the determinant (b2 - 4ac)

double determinant = b * b - 4 * a * c;

// check if determinant is greater than 0

if (determinant > 0) {

// two real and distinct roots

root1 = (-b + Math.sqrt(determinant)) / (2 * a);

root2 = (-b - Math.sqrt(determinant)) / (2 * a);

System.out.format("root1 = %.2f and root2 = %.2f", root1, root2);

// check if determinant is equal to 0

else if (determinant == 0) {

OOP USING JAVA LABORATORY (22SCS033) Page 1


// two real and equal roots

// determinant is equal to 0

// so -b + 0 == -b

root1 = root2 = -b / (2 * a);

System.out.format("root1 = root2 = %.2f;", root1);

// if determinant is less than zero

else

// roots are complex number and distinct

double real = -b / (2 * a);

double imaginary = Math.sqrt(-determinant) / (2 * a);

System.out.format("root1 = %.2f+%.2fi", real, imaginary);

System.out.format("\nroot2 = %.2f-%.2fi", real, imaginary);

Output:

root1 = -0.87+1.30i and root2 = -0.87-1.30i

OOP USING JAVA LABORATORY (22SCS033) Page 2


2. a. Write a Java program that works as a simple calculator

import java.util.Scanner;

class Main {

public static void main(String[] args) {

char operator;

Double number1, number2, result;

// create an object of Scanner class

Scanner input = new Scanner(System.in);

// ask users to enter operator

System.out.println("Choose an operator: +, -, *, or /");

operator = input.next().charAt(0);

// ask users to enter numbers

System.out.println("Enter first number");

number1 = input.nextDouble();

System.out.println("Enter second number");

number2 = input.nextDouble();

switch (operator) {

// performs addition between numbers

OOP USING JAVA LABORATORY (22SCS033) Page 3


case '+':

result = number1 + number2;

System.out.println(number1 + " + " + number2 + " = " + result);

break;

// performs subtraction between numbers

case '-':

result = number1 - number2;

System.out.println(number1 + " - " + number2 + " = " + result);

break;

// performs multiplication between numbers

case '*':

result = number1 * number2;

System.out.println(number1 + " * " + number2 + " = " + result);

break;

// performs division between numbers

case '/':

result = number1 / number2;

System.out.println(number1 + " / " + number2 + " = " + result);

break;

default:

System.out.println("Invalid operator!");

break;

OOP USING JAVA LABORATORY (22SCS033) Page 4


input.close();

Output:

Choose an operator: +, -, *, or /

Enter first number

Enter second number

3.0 * 9.0 = 27.

OOP USING JAVA LABORATORY (22SCS033) Page 5


b. Write a Java program to sort for an element in a given list of elements using bubble
sort.

import java.util.Scanner;

public class BSort

public static void Sort(int a[])

int n=a.length,i,j,p,temp;

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

for (j=0; j<n-i-1; j++)

if(a[j+1]<a[j])

{temp=a[j+1];

a[j+1]=a[j];

a[j]=temp;}

public static void printarray(int a[])

for(int i=0; i < a.length; i++)

OOP USING JAVA LABORATORY (22SCS033) Page 6


{

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

public static void main(String[] args)

int n, res,i;

Scanner s = new Scanner(System.in);

System.out.print("Enter number of elements in the array:");

n = s.nextInt();

int a[] = new int[n];

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

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

a[i] = s.nextInt();

System.out.println( "elements in array ");

printarray(a);

Sort(a);

System.out.println( "\nelements after sorting");

printarray(a);

OOP USING JAVA LABORATORY (22SCS033) Page 7


}

Output:

Enter number of elements in the array:5

Enter 5 elements

elements in array

5 4 3 2 1

elements after sorting

1 2 3 4 5

OOP USING JAVA LABORATORY (22SCS033) Page 8


3. Create a Java class called Student with the following details as variables within it.

(i) USN

(ii) Name

(iii) Branch

(iv) Phone

Write a Java program to create n Student objects and print the USN, Name, Branch,
and Phone of these
objects with suitable headings.

import java.util.Scanner; public class student

String USN;

String Name;

String branch;

int phone;

void insertRecord(String reg,String name, String brnch,int ph) {

USN=reg;

Name=name;

branch=brnch;

phone=ph;

void displayRecord()

System.out.println(USN+" "+Name+" "+branch+" "+phone);

public static void main(String args[])

OOP USING JAVA LABORATORY (22SCS033) Page 9


{

student s[]=new student [100];

Scanner sc=new Scanner(System.in);

System.out.println("enter the number of students");

int n=sc.nextInt();

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

s[i]=new student();

for(int j=0;j<n;j++)

{ System.out.println("enter the usn,name,branch,phone")

String USN=sc.next();

String Name=sc.next();

String branch=sc.next();

int phone=sc.nextInt();

s[j].insertRecord(USN,Name,branch,phone);

for( int m=0;m<n;m++)

s[m].displayRecord();

OOP USING JAVA LABORATORY (22SCS033) Page 10


Output:

enter the number of students

enter the usn,name,branch,phone

monika

cse

93411

enter the usn,name,branch,phone

12

gowda

cse 9785

students details are

1 monika cse 93411

12 gowda cse 9785

OOP USING JAVA LABORATORY (22SCS033) Page 11


4. a. Write a Java Program to define a class, define instance methods and overload them
and use them for dynamic method invocation.

import java.lang.*;

class add
{
void display(int a,int b)
{
int c=a+b;
System.out.println("The sum of " + a + " & " + b + " is " + c);
}
void display(double a,double b)
{ double c=a+b;
System.out.println("The sum of " + a + " & " + b + " is " + c);

}
}
class add_demo
{
public static void main(String arg[])
{
add obj=new add();
obj.display(10,20);
obj.display(10.2,20.2);
}
}

Output:
The sum of 10 & 20 is 30
The sum of 10.2 & 20.2 is 30.4

OOP USING JAVA LABORATORY (22SCS033) Page 12


b. Write a java program for abstract class to find areas of different shapes

abstract class shape

abstract double area();

class rectangle extends shape

double l=12.5,b=2.5;

double area()

return l*b;

class triangle extends shape

double b=4.2,h=6.5;

double area()

return 0.5*b*h;

class square extends shape

OOP USING JAVA LABORATORY (22SCS033) Page 13


{

double s=6.5;

double area()

return 4*s;

class shapedemo

public static void main(String[] args)

rectangle r1=new rectangle();

triangle t1=new triangle();

square s1=new square();

System.out.println("The area of rectangle is: "+r1.area());

System.out.println("The area of triangle is: "+t1.area());

System.out.println("The area of square is: "+s1.area());}

Output:

The area of rectangle is: 31.25

The area of triangle is: 13.65

The area of square is: 26.0

OOP USING JAVA LABORATORY (22SCS033) Page 14


5. Design a superclass called Staff with details as StaffId, Name, Phone, Salary. Extend
this class by writing three subclasses namely Teaching (domain, publications),
Technical (skills), and Contract (period). Write a Java program to read and display at
least 3 staff objects of all three categories.

class Staff {
int staffid,
String phone,
int salary;
String name;
Staff(int id , int no, int sal, String na){
staffid=id;
phone=no;
salary=sal;
name=na;
}
void display(){
System.out.println("-------------------------------------");
System.out.println("Staff ID:"+ " "+ staffid);
System.out.println("Staff Phone number:" + " "+ phone);
System.out.println("Staff Salary:" +" "+ salary);
System.out.println("Staff Name:" +" "+ name);
}
}
class Teaching extends Staff {
String domain;
int no_of_publications;
public Teaching(int id, int no, int sal, String na,String d,int nop){
super(id,no,sal,na);
domain=d;
no_of_publications=nop;
}
void Tdisplay(){
System.out.println("-------------------------------------");
System.out.println("Teaching Staff Details");
super.display();
System.out.println("Domain :" +" "+domain);
System.out.println("No_of_publications:"+" "+no_of_publications);
}
}
class Technical extends Staff{
String skills;
public Technical(int id , int no, int sal, String na,String sk){
super(id,no,sal,na);
skills=sk;
}
void Tedisplay(){
System.out.println("-------------------------------------");

OOP USING JAVA LABORATORY (22SCS033) Page 15


System.out.println("Technical Staff Details");
super.display();
System.out.println("Skills :" + " "+skills);
}
}
class Contract extends Staff{
int period;
public Contract(int id , int no, int sal, String na,int pd){
super(id,no,sal,na);
period=pd;

}
void Cdisplay(){
System.out.println("-------------------------------------");
System.out.println("Contract Staff Details");
super.display();
System.out.println("ContractPeriod:" + " "+period + "years");
}
}
public class Multilevel{
public static void main(String args[]){
Teaching t1=new Teaching(11,998765434,31000,"Anil","CSE",10);
Teaching t2=new Teaching(12,996655546,30000,"Anu","ISE",9);
Teaching t3=new Teaching(13,999933442,32000,"Anusha","EEE",8);
t1.Tdisplay();
t2.Tdisplay();
t3.Tdisplay();
Technical te1=new Technical(21,994433221,22000,"Kumar","C");
Technical te2=new Technical(22,998877665,28000,"Krisna","Java");
Technical te3=new Technical(23,991654321,33000,"Kiran","Java");
te1.Tedisplay();
te2.Tedisplay();
te3.Tedisplay();”
Contract ct1=new Contract(31,”998765434”,35000,"Anil",3);
Contract ct2=new Contract(32,912345678,39000,"Meghana",2);
Contract ct3=new Contract(33,992233445,30000,"Uma",4);
ct1.Cdisplay();
ct2.Cdisplay();
ct3.Cdisplay();
}
}

Output:

Output:
-------------------------------------

OOP USING JAVA LABORATORY (22SCS033) Page 16


Teaching Staff Details
-------------------------------------
Staff ID: 11
Staff Phone number: 998765434
Staff Salary: 31000
Staff Name: Anil
Domain : CSE
No_of_publications: 10
-------------------------------------
Teaching Staff Details
-------------------------------------
Staff ID: 12
Staff Phone number: 996655546
Staff Salary: 30000
Staff Name: Anu
Domain : ISE
No_of_publications: 9
-------------------------------------
Teaching Staff Details
-------------------------------------
Staff ID: 13
Staff Phone number: 999933442
Staff Salary: 32000
Staff Name: Anusha
Domain : EEE
No_of_publications: 8

-------------------------------------
Technical Staff Details
-------------------------------------
Staff ID: 21
Staff Phone number: 994433221
Staff Salary: 22000
Staff Name: Kumar
Skills : C
-------------------------------------
Technical Staff Details
-------------------------------------
Staff ID: 22
Staff Phone number: 998877665
Staff Salary: 28000
Staff Name: Krisna
Skills : Java
-------------------------------------
Technical Staff Details
-------------------------------------
Staff ID: 23
Staff Phone number: 991654321

OOP USING JAVA LABORATORY (22SCS033) Page 17


Staff Salary: 33000
Staff Name: Kiran
Skills : Java
-------------------------------------
Contract Staff Details
-------------------------------------
Staff ID: 31
Staff Phone number: 998765434
Staff Salary: 35000
Staff Name: Anil
ContractPeriod: 3years
-------------------------------------
Contract Staff Details
-------------------------------------
Staff ID: 32
Staff Phone number: 912345678
Staff Salary: 39000
Staff Name: Meghana
ContractPeriod: 2years
-------------------------------------
Contract Staff Details
-------------------------------------
Staff ID: 33
Staff Phone number: 992233445
Staff Salary: 30000
Staff Name: Uma
ContractPeriod: 4years

OOP USING JAVA LABORATORY (22SCS033) Page 18


6. Write a Java class called Customer to store their name and date_of_birth. The
date_of_birth format should be dd/mm/yyyy. Write methods to read customer data as
<name, dd,mm,yyyy> and display

import java.util.Scanner;
import java.util.StringTokenizer;
class customer
{
String name;
String date;
public void read()
{
Scanner input =new Scanner(System.in);
name=input.next();
date=input.next();
}
public void display()
{
System.out.print(name+",");
String delims="/";
StringTokenizer st=new StringTokenizer(date,delims);
while(st.hasMoreElements()){
System.out.print(st.nextElement()+",");
}
System.out.println();
}
public static void main(String[] args)
{
customer[] cus=new customer[30];
Scanner sc =new Scanner(System.in);

System.out.println("enter the number of customer");


int n=sc.nextInt();
System.out.println("Enter the customer detail");

for(int i=0;i<n;i++)
{
cus[i]=new customer();
cus[i].read();
}
for(int i=0;i<n;i++)
cus[i].display();
}
}

OOP USING JAVA LABORATORY (22SCS033) Page 19


Output:

Enter the customer detail


enter the number of customer
2
Enter the customer name and date
rama
12/2/2018
laxman
11/4/2018

rama,12,2,2018,
laxman,11,4,2018,

OOP USING JAVA LABORATORY (22SCS033) Page 20


7. Write a Java program that implements a multi-thread application that has three
threads. First thread generates a random integer for every 1 second; second thread
computes the square of the number and prints; third thread will print the value of cube
of the number.

import java.util.Random;

class Square extends Thread

int x;

Square(int n)

x = n;

public void run()

int sqr = x * x;

System.out.println("Square of " + x + " = " + sqr );

OOP USING JAVA LABORATORY (22SCS033) Page 21


}

class Cube extends Thread

int x;

Cube(int n)

x = n;

public void run()

int cub = x * x * x;

System.out.println("Cube of " + x + " = " + cub );

class Number extends Thread

public void run()

OOP USING JAVA LABORATORY (22SCS033) Page 22


{

Random random = new Random();

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

int r = random.nextInt(100);

System.out.println("Random Integer generated : " + r);

Square s = new Square(r);

s.start();

Cube c = new Cube(r);

c.start();

try {

Thread.sleep(1000);

} catch (InterruptedException ex) {

System.out.println(ex);

OOP USING JAVA LABORATORY (22SCS033) Page 23


}

public class LAB3B {

public static void main(String args[])

Number n = new Number();

n.start();

Output:

Random Integer generated : 82

Square of 82 = 6724

Cube of 82 = 551368

Random Integer generated : 34

Square of 34 = 1156

Cube of 34 = 39304

Random Integer generated : 17

Square of 17 = 289

OOP USING JAVA LABORATORY (22SCS033) Page 24


Cube of 17 = 4913

Random Integer generated : 84

Square of 84 = 7056

Cube of 84 = 592704

Random Integer generated : 34

Cube of 34 = 39304

Square of 34 = 1156

Random Integer generated : 51

Square of 51 = 2601

Cube of 51 = 132651

Random Integer generated : 38

Square of 38 = 1444

Cube of 38 = 54872

Random Integer generated : 94

Square of 94 = 8836

Cube of 94 = 830584

Random Integer generated : 65

OOP USING JAVA LABORATORY (22SCS033) Page 25


Cube of 65 = 274625

Square of 65 = 4225

Random Integer generated : 75

Square of 75 = 5625

Cube of 75 = 421875

OOP USING JAVA LABORATORY (22SCS033) Page 26


8. Write a java program that displays the number of characters, lines and words in a
text file.

import java.io.*;
class FileDemo

{
public static void main(String args[])

{
try

int lines=0,chars=0,words=0;
int code=0;

FileInputStream fis = new FileInputStream("sample.txt");


while(fis.available()!=0)

{
code = fis.read();

if(code!=10)// no further records exists

chars++;
if(code==32)//
words++;
if(code==13)

{
lines++;

words++;

}
}

System.out.println("No.of characters = "+chars);


System.out.println("No.of words = "+(words+1));
System.out.println("No.of lines = "+(lines+1));

OOP USING JAVA LABORATORY (22SCS033) Page 27


fis.close();

}
catch(FileNotFoundException e)

{
System.out.println("Cannot find the specified file...");

}
catch(IOException i)

System.out.println("Cannot read file...");


}

}
}

Output:

Content in sample.txt file is:


He is
a good
boy

Input and output for the above program is as follows:

No.of characters = 16
No.of words = 5
No.of lines = 3

OOP USING JAVA LABORATORY (22SCS033) Page 28


9. Write a java program that reads a file and displays the file on the screen with line
number b.

import java.io.*;

import java.util.*;

class ReadFile{

public static void main(String[] args){

Scanner input = new Scanner(System.in);

System.out.print("Enter the name of the file: ");

String file_name = input.nextLine();

File f = new File(file_name);

int i;

boolean wrong=true;

while(wrong)

OOP USING JAVA LABORATORY (22SCS033) Page 29


try{

FileReader finp = new FileReader(f);

LineNumberReader linereader = new LineNumberReader(finp);

while((i=linereader.read())!=-1)

System.out.println("Line #:"+(linereader.getLineNumber()+1));

System.out.println((char)i+linereader.readLine());

wrong=false;

catch(FileNotFoundException e){

System.out.println("File does not exist, ");

System.out.print("Enter another file name:");

file_name = input.nextLine();

OOP USING JAVA LABORATORY (22SCS033) Page 30


f = new File(file_name);

catch(IOException e){

System.out.println("Cannot Read file:");

OOP USING JAVA LABORATORY (22SCS033) Page 31


10. Write a Java program that works as a simple calculator. Use a grid layout to
arrange buttons for the digits and for the +, -,*, % operations. Add a text field to
display the result. Handle any possible exceptions like divide by zero.

/* Program to create a Simple Calculator */


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
/*
<applet code="MyCalculator" width=300 height=300>
</applet>
*/
public class MyCalculator extends Applet implements ActionListener {
int num1,num2,result;
TextField T1;
Button NumButtons[]=new Button[10];
Button Add,Sub,Mul,Div,clear,EQ;
char Operation;
Panel nPanel,CPanel,SPanel;
public void init() {
nPanel=new Panel();
T1=new TextField(30);
nPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
nPanel.add(T1);
CPanel=new Panel();
CPanel.setBackground(Color.white);
CPanel.setLayout(new GridLayout(5,5,3,3));
for(int i=0;i<10;i++) {
NumButtons[i]=new Button(""+i);
}
Add=new Button("+");
Sub=new Button("-");
Mul=new Button("*");
Div=new Button("/");
clear=new Button("clear");
EQ=new Button("=");
T1.addActionListener(this);
for(int i=0;i<10;i++) {
CPanel.add(NumButtons[i]);
}
CPanel.add(Add);
CPanel.add(Sub);
CPanel.add(Mul);
CPanel.add(Div);
CPanel.add(EQ);

OOP USING JAVA LABORATORY (22SCS033) Page 32


SPanel=new Panel();
SPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
SPanel.setBackground(Color.yellow);
SPanel.add(clear);
for(int i=0;i<10;i++) {
NumButtons[i].addActionListener(this);
}
Add.addActionListener(this);
Sub.addActionListener(this);
Mul.addActionListener(this);
Div.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
this.setLayout(new BorderLayout());
add(nPanel,BorderLayout.NORTH);
add(CPanel,BorderLayout.CENTER);
add(SPanel,BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent ae) {
String str=ae.getActionCommand ();
char ch=str.charAt(0);
if(Character.isDigit(ch))
T1.setText(T1.getText()+str);
else
if(str.equals("+")){
num1=Integer.parseInt (T1.getText());
Operation='+';
T1.setText ("");
}
if(str.equals("-")){
num1=Integer.parseInt(T1.getText());
Operation='-';
T1.setText("");
}
if(str.equals("*")){
num1=Integer.parseInt(T1.getText());
Operation='*';
T1.setText("");
}
if(str.equals("/")){
num1=Integer.parseInt(T1.getText());
Operation='/';
T1.setText("");
}
if(str.equals("%")){
num1=Integer.parseInt(T1.getText());
Operation='%';
T1.setText("");
}
if(str.equals("=")) {

OOP USING JAVA LABORATORY (22SCS033) Page 33


num2=Integer.parseInt(T1.getText());
switch(Operation)
{
case '+':result=num1+num2;
break;
case '-':result=num1-num2;
break;
case '*':result=num1*num2;
break;
case '/':try {
result=num1/num2;
}
catch(ArithmeticException e) {
result=num2;
JOptionPane.showMessageDialog(this,"Divided by zero");
}
break;
}
T1.setText(""+result);
}
if(str.equals("clear")) {
T1.setText("");
}
}
}

Output

OOP USING JAVA LABORATORY (22SCS033) Page 34


OOP USING JAVA LABORATORY (22SCS033) Page 35
OOP USING JAVA LABORATORY (22SCS033) Page 36

You might also like