DR. B.C.
ROY ENGINEERING COLLEGE
DURGAPUR, WEST BENGAL
Lab Assignment
Submitted By:
Name : Tukai Ghosh
University Roll : 12071023052
Semester : 2nd Sem
Paper Name : Object Oriented Programming lab
using Java
Paper Code : MCAN-293
Department : MCA
DR. B.C. ROY ENGINEERING COLLEGE
DURGAPUR, WEST BENGAL
Lab Assignment
Submitted By:
Name : Subrata Kar
University Roll : 120710230
Semester : 2nd Sem
Paper Name : Object Oriented Programming lab
using Java
Paper Code : MCAN-293
Department : MCA
DR. B.C. ROY ENGINEERING COLLEGE
DURGAPUR, WEST BENGAL
Lab Assignment
Submitted By:
Name : Suman Dutta
University Roll : 12071023049
Semester : 2nd Sem
Paper Name : Object Oriented Programming lab
using Java
Paper Code : MCAN-293
Department : MCA
DR. B.C. ROY ENGINEERING COLLEGE
DURGAPUR, WEST BENGAL
Lab Assignment
Submitted By:
Name : Ravi Kumar
University Roll : 12071023032
Semester : 2nd Sem
Paper Name : Object Oriented Programming lab
using Java
Paper Code : MCAN-293
Department : MCA
DR. B.C. ROY ENGINEERING COLLEGE
DURGAPUR, WEST BENGAL
Lab Assignment
Submitted By:
Name : Koushik Roy
University Roll : 12071023015
Semester : 2nd Sem
Paper Name : Object Oriented Programming lab
using Java
Paper Code : MCAN-293
Department : MCA
DR. B.C. ROY ENGINEERING COLLEGE
DURGAPUR, WEST BENGAL
Lab Assignment
Submitted By:
Name : Biplob Mondal
University Roll : 12071023012
Semester : 2nd Sem
Paper Name : Object Oriented Programming lab
using Java
Paper Code : MCAN-293
Department : MCA
DR. B.C. ROY ENGINEERING COLLEGE
DURGAPUR, WEST BENGAL
Lab Assignment
Submitted By:
Name : Shiltu Dey
University Roll : 12071023041
Semester : 2nd Sem
Paper Name : Object Oriented Programming lab
using Java
Paper Code : MCAN-293
Department : MCA
1. Create a class representing a "Book" with attributes such as title, author, and price.
Implement a parameterized constructor to initialize these attributes and methods to display
book details.
Ans :-
class Book {
private String title;
private String author;
private double price;
public Book(String title, String author, double price) {
this.title = title;
this.author = author;
this.price = price;
}
public void displayDetails() {
System.out.println("Title: " +
title);
System.out.println("Author: " +
author); System.out.println("Price: $" +
price);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
public class Main {
public static void main(String[] args) {
Book book1 = new Book("The Great Gatsby", "F. Scott Fitzgerald", 10.99);
book1.displayDetails();
}
}
Output:
Title: The Great Gatsby
Author: F. Scott Fitzgerald
Price: $10.99
2. Develop a program to demonstrate constructor overloading by creating multiple constructors for a class.
Ans :-
public class Box {
private double length;
private double width;
private double height;
public Box() {
length = 1.0;
width = 1.0;
height = 1.0;
}
public Box(double side) {
length = side;
width = side;
height = side;
}
public Box(double length, double width, double height) {
this.length = length;
this.width = width;
this.height = height;
}
public double calculateVolume()
{ return length * width *
height;
}
public void displayDimensions() {
System.out.println("Length: " + length);
System.out.println("Width: " + width);
System.out.println("Height: " + height);
}
public static void main(String[] args) {
Box box1 = new Box();
Box box2 = new Box(2.0);
Box box3 = new Box(3.0, 4.0,
5.0); System.out.println("Box
1:");
box1.displayDimensions();
System.out.println("Volume: " + box1.calculateVolume());
System.out.println();
System.out.println("Box 2:");
box2.displayDimensions();
System.out.println("Volume: " + box2.calculateVolume());
System.out.println();
System.out.println("Box 3:");
box3.displayDimensions();
System.out.println("Volume: " + box3.calculateVolume());
}
}
Output :-
Box 1:
Length: 1.0
Width: 1.0
Height: 1.0
Volume: 1.0
Box 2:
Length: 2.0
Width: 2.0
Height: 2.0
Volume: 8.0
Box 3:
Length: 3.0
Width: 4.0
Height: 5.0
Volume: 60.0
3. Design a class hierarchy for different types of vehicles (e.g., Car, Bike, Truck) with common attributes
like make, model, and year. Implement inheritance to avoid code duplication. Include a superclass
"Vehicle" with methods like start() and stop(). Override these methods in subclasses to provide
specific
implementations for each type of vehicle.
Ans: -
class Vehicle {
private String make;
private String model;
private int year;
public Vehicle(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
public void start() {
System.out.println("Starting the vehicle...");
}
public void stop() {
System.out.println("Stopping the vehicle...");
}
}
class Car extends Vehicle {
private int numberOfDoors;
public Car(String make, String model, int year, int numberOfDoors) {
super(make, model, year);
this.numberOfDoors = numberOfDoors;
}
@Override
public void start() {
System.out.println("Starting the car engine...");
}
@Override
public void stop() {
System.out.println("Stopping the car engine...");
}
}
class Bike extends Vehicle {
private boolean hasGears;
public Bike(String make, String model, int year, boolean hasGears) {
super(make, model, year);
this.hasGears = hasGears;
}
@Override
public void start() {
System.out.println("Starting the bike engine...");
}
@Override
public void stop() {
System.out.println("Stopping the bike engine...");
}
}
class Truck extends Vehicle {
private int loadCapacity;
public Truck(String make, String model, int year, int loadCapacity) {
super(make, model, year);
this.loadCapacity = loadCapacity;
}
@Override
public void start() {
System.out.println("Starting the truck engine...");
}
@Override
public void stop() {
System.out.println("Stopping the truck engine...");
}
}
public class VMain {
public static void main(String[] args) {
// Create objects of different types of vehicles
Car car = new Car("Toyota", "Camry", 2021, 4);
Bike bike = new Bike("Honda", "CBR1000RR", 2021, true);
Truck truck = new Truck("Ford", "F-150", 2021, 5000);
car.start();
car.stop();
bike.start();
bike.stop();
truck.start();
truck.stop();
}
}
Output :-
Starting the car engine...
Stopping the car engine...
Starting the bike engine...
Stopping the bike engine...
Starting the truck engine...
Stopping the truck engine...
4. Create an interface "Shape" with a method calculateArea(). Implement this interface with classes
representing different geometric shapes (e.g., Circle, Rectangle, Triangle). Use polymorphism to
calculate and display the area of each shape.
Ans :-
interface Shape {
double calculateArea();
}
class Circle implements Shape {
private double radius;
public Circle(double radius)
{ this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
class Rectangle implements Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double calculateArea()
{ return length * width;
}
}
class Triangle implements Shape {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
public double calculateArea()
{ return 0.5 * base * height;
}
}
public class ShapeMain {
public static void main(String[] args) {
Shape circle = new Circle(5);
Shape rectangle = new Rectangle(4,
6); Shape triangle = new Triangle(3, 7);
System.out.println("Area of Circle: " + circle.calculateArea());
System.out.println("Area of Rectangle: " + rectangle.calculateArea());
System.out.println("Area of Triangle: " + triangle.calculateArea());
}
}
Output:-
Area of Circle: 78.53981633974483
Area of Rectangle: 24.0
Area of Triangle: 10.5
5. Design a class representing a "BankAccount" with private attributes such as account number,
balance, and account holder name. Use encapsulation to provide public methods for deposit,
withdrawal, and displaying account details while ensuring data integrity.
Ans: -
class BankAccount {
private int
accountNumber; private
double balance;
private String accountHolderName;
public BankAccount(int accountNumber, String accountHolderName) {
this.accountNumber = accountNumber;
this.accountHolderName = accountHolderName;
this.balance = 0.0; // Initialize balance to 0
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposit of $" + amount + " successful.");
} else {
System.out.println("Invalid amount for deposit.");
}
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrawal of $" + amount + " successful.");
} else {
System.out.println("Invalid amount for withdrawal or insufficient funds.");
}
}
public void displayAccountDetails() {
System.out.println("Account Number: " + accountNumber);
System.out.println("Account Holder Name: " + accountHolderName);
System.out.println("Balance: $" + balance);
}
public int getAccountNumber()
{ return accountNumber;
}
public double getBalance() {
return balance;
}
public String getAccountHolderName() {
return accountHolderName;
}
public void setAccountHolderName(String accountHolderName) {
this.accountHolderName = accountHolderName;
}
}
public class BankAccountMain {
public static void main(String[] args) {
BankAccount account = new BankAccount(123456, "John Doe");
account.deposit(500);
System.out.println("Account Details after Deposit:");
account.displayAccountDetails();
account.withdraw(200);
System.out.println("Account Details after Withdrawal:");
account.displayAccountDetails();
}
}
Output :-
Account Number: 123456
Account Holder Name: John Doe
Balance: $500.0
Withdrawal of $200.0 successful.
Account Details after
Withdrawal: Account Number:
123456
Account Holder Name: John Doe
Balance: $300.0
6. Write a Java program which will contain the user-defined package Calculator with all 4 basic
arithmetic operations in a class and another class in package will contain operations like Square and
Square Root (use Math.sqrt()) method.
Ans :-
package calculator;
public class BasicCalculator {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
public int multiply(int a, int b) {
return a * b;
}
public double divide(int a, int b) {
if (b != 0) {
return (double) a / b;
} else {
throw new IllegalArgumentException("Cannot divide by zero.");
}
}
}
package calculator;
public class AdvancedCalculator {
public double square(int a) {
return a * a;
}
public double squareRoot(double a) {
return Math.sqrt(a);
}
}
import calculator.*;
public class CalculatorMain {
public static void main(String[] args) {
// Basic calculator operations
BasicCalculator basicCalc = new BasicCalculator();
System.out.println("Addition: " + basicCalc.add(10, 5));
System.out.println("Subtraction: " + basicCalc.subtract(10, 5));
System.out.println("Multiplication: " + basicCalc.multiply(10, 5));
System.out.println("Division: " + basicCalc.divide(10, 5));
// Advanced calculator operations
AdvancedCalculator advancedCalc = new AdvancedCalculator();
System.out.println("Square: " + advancedCalc.square(5));
System.out.println("Square Root: " + advancedCalc.squareRoot(25));
}
}
Output :-
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
Square: 25.0
Square Root: 5.0
7. Write a Java program to calculate the area and perimeter of a rectangle.
Ans:-
import java.util.Scanner;
public class RectangleCalculator {
public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
System.out.println("Enter the length of the rectangle:");
double length = scanner.nextDouble();
System.out.println("Enter the width of the rectangle:");
double width = scanner.nextDouble();
// Calculate area and perimeter
double area = calculateArea(length, width);
double perimeter = calculatePerimeter(length, width);
System.out.println("Area of the rectangle: " + area);
System.out.println("Perimeter of the rectangle: " + perimeter);
scanner.close();
}
// Method to calculate the area of the rectangle
public static double calculateArea(double length, double width) {
return length * width;
}
// Method to calculate the perimeter of the rectangle
public static double calculatePerimeter(double length, double width) {
return 2 * (length + width);
}
}
Output:-
Enter the length of the rectangle:
3
Enter the width of the rectangle:
4
Area of the rectangle: 12.0
Perimeter of the rectangle: 14.0
8. Create a program to find the factorial of a given number using iterative approaches.
Ans:-
import java.util.Scanner;
public class FactorialCalculator {
public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
System.out.print("Enter a non-negative integer: ");
int number = scanner.nextInt();
if (number < 0) {
System.out.println("Factorial is not defined for negative numbers.");
} else {
long factorial = calculateFactorial(number);
System.out.println("Factorial of " + number + " is: " + factorial);
}
scanner.close();
}
// Method to calculate factorial using an iterative approach
public static long calculateFactorial(int number) {
if (number == 0 || number == 1) {
return 1;
}
long factorial = 1;
for (int i = 2; i <= number; i++)
{ factorial *= i;
}
return factorial;
}
}
Output:-
Enter a non-negative integer:
5 Factorial of 5 is: 120
9. Implement a simple calculator program that performs basic arithmetic operations
(addition, subtraction, multiplication, division).
Ans:-
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
// Prompt the user to enter two numbers
System.out.print("Enter the first number:
"); double num1 = scanner.nextDouble();
System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();
// Perform arithmetic operations
double sum = num1 + num2;
double difference = num1 -
num2; double product = num1 *
num2; double quotient = num1 /
num2;
// Display results
System.out.println("Sum: " + sum);
System.out.println("Difference: " + difference);
System.out.println("Product: " + product);
System.out.println("Quotient: " + quotient);
scanner.close();
}
}
Output:-
Enter the first number: 4
Enter the second number:
3 Sum: 7.0
Difference: 1.0
Product: 12.0
Quotient: 1.3333333333333333
10. Implement a program that reads a sequence of integers from the user until a negative
number is entered, then calculates and displays the sum and average of the entered
numbers.
Ans:-
import java.util.Scanner;
public class SumAndAverageCalculator
{ public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int sum = 0;
int count = 0;
System.out.println("Enter a sequence of integers (enter a negative number to stop):");
while (true) {
int num = scanner.nextInt();
// Check if the entered number is negative
if (num < 0) {
break; // Exit the loop if a negative number is entered
}
sum += num; // Add the number to the sum
count++; // Increment the count of numbers entered
}
// Check if any numbers were
entered if (count > 0) {
// Calculate the average
double average = (double) sum / count;
// Display the sum and average
System.out.println("Sum of the entered numbers: " + sum);
System.out.println("Average of the entered numbers: " + average);
} else {
System.out.println("No numbers were entered.");
}
scanner.close();
}
}
Output:-
Enter a sequence of integers (enter a negative number to stop):
10
2
8
4
-1
Sum of the entered numbers: 24
Average of the entered numbers: 6.0
11. Write a Java program to check whether a given year is a leap year or not.
Ans:
import java.util.Scanner;
public class LeapYearChecker {
public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
System.out.print("Enter the year:
"); int year = scanner.nextInt();
boolean isLeapYear = checkLeapYear(year);
if (isLeapYear) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}
scanner.close();
}
// Method to check if a year is a leap year
public static boolean checkLeapYear(int year) {
// Leap year is divisible by 4, but not divisible by 100, unless it is also divisible by 400
return (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0);
}
}
Output:-
Enter the year: 2024
2024 is a leap year.
12. Create a program to find the largest and smallest elements in an array of integers.
Ans:-
import java.util.Scanner;
public class ArrayMinMaxFinder {
public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
// Input the size of the array
System.out.print("Enter the size of the array:
"); int size = scanner.nextInt();
// Create an array of the specified
size int[] arr = new int[size];
// Input elements of the array
System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
arr[i] = scanner.nextInt();
}
// Find the largest and smallest elements
int largest = arr[0];
int smallest = arr[0];
for (int i = 1; i < size; i++)
{ if (arr[i] > largest) {
largest = arr[i];
}
if (arr[i] < smallest) {
smallest = arr[i];
}
}
// Display the largest and smallest elements
System.out.println("Largest element in the array: " + largest);
System.out.println("Smallest element in the array: " + smallest);
scanner.close();
}
}
Output:-
Enter the size of the array: 5
Enter the elements of the
array: 6
-1
2
3
0
Largest element in the array: 6
Smallest element in the array: -
1
13. Write a program to find the sum of elements in a 2D array and calculate the average.
Ans:-
import java.util.Scanner;
public class Array2DSumAndAverage {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the dimensions of the 2D array
System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();
System.out.print("Enter the number of columns: ");
int columns = scanner.nextInt();
// Create a 2D array with the specified dimensions
int[][] arr = new int[rows][columns];
// Input elements of the array
System.out.println("Enter the elements of the array:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) { arr[i]
[j] = scanner.nextInt();
}
}
// Calculate sum of
elements int sum = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
sum += arr[i][j];
}
}
// Calculate average
double average = (double) sum / (rows * columns);
// Display sum and average
System.out.println("Sum of elements in the 2D array: " + sum);
System.out.println("Average of elements in the 2D array: " + average);
scanner.close();
}
}
Output:-
Enter the number of rows: 3
Enter the number of columns: 3
Enter the elements of the array:
123
456
789
Sum of elements in the 2D array: 45
Average of elements in the 2D array: 5.0
14. Implement a method to check whether a given number is prime or not, and use it to find all prime
numbers within a given range.
Ans:-
import java.util.Scanner;
public class PrimeNumberFinder {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the range
System.out.print("Enter the lower bound of the range: ");
int lowerBound = scanner.nextInt();
System.out.print("Enter the upper bound of the range: ");
int upperBound = scanner.nextInt();
System.out.println("Prime numbers within the range [" + lowerBound + ", " + upperBound +
"]:");
// Find and print all prime numbers within the range
for (int i = lowerBound; i <= upperBound; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
scanner.close();
}
// Method to check if a number is prime
public static boolean isPrime(int number)
{
if (number <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
Output:-
Enter the lower bound of the range: 10
Enter the upper bound of the range: 30
Prime numbers within the range [10, 30]:
11 13 17 19 23 29
15. Using static method with the implementation of constructor write the program to implement counter.
Ans:-
public class Counter {
private static int count = 0;
// Constructor
public Counter() {
count++; // Increment count every time a new Counter object is created
}
// Static method to get the current count
public static int getCount() {
return count;
}
public static void main(String[] args) {
// Create multiple Counter objects
Counter counter1 = new
Counter(); Counter counter2 =
new Counter(); Counter counter3
= new Counter();
// Print the count
System.out.println("Count: " + Counter.getCount()); // Output: 3
}
}
Output:-
Count: 3
16) Write a Java program to perform the following operations on an array:
Find the maximum and minimum elements.
Calculate the sum and average of the
elements. Reverse the array.
Ans : public class ArrayOperations {
public static void main(String[] args) {
int[] array = {3, 5, 7, 2, 8, -1, 4, 10, 12};
// Find maximum and minimum elements
int max = findMax(array);
int min = findMin(array);
System.out.println("Maximum element: " +
max); System.out.println("Minimum element: " +
min);
// Calculate sum and average of the elements
int sum = calculateSum(array);
double average = calculateAverage(array);
System.out.println("Sum of elements: " + sum);
System.out.println("Average of elements: " + average);
// Reverse the
array
reverseArray(array);
System.out.println("Reversed array: ");
for (int i : array) {
System.out.print(i + " ");
}
}
// Method to find the maximum element in the array
public static int findMax(int[] array) {
int max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
// Method to find the minimum element in the array
public static int findMin(int[] array) {
int min = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
}
}
return min;
}
// Method to calculate the sum of the elements in the array
public static int calculateSum(int[] array) {
int sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
}
return sum;
}
// Method to calculate the average of the elements in the array
public static double calculateAverage(int[] array) {
int sum = calculateSum(array);
return (double) sum /
array.length;
}
// Method to reverse the array
public static void reverseArray(int[] array)
{ int start = 0;
int end = array.length -
1; while (start < end) {
int temp = array[start];
array[start] =
array[end]; array[end] =
temp;
start++;
end--;
}
}
}
Output:
Maximum element: 12
Minimum element: -1
Sum of elements: 50
Average of elements:
5.555555555555555 Reversed array:
12 10 4 -1 8 2 7 5 3
17) Create a base class Person with attributes like name and age. Create a derived class Student that
adds an attribute for student ID. Write methods to display the details of both classes.
Ans:-
// Base class Person
class Person {
// Attributes
protected String name;
protected int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Method to display details
public void displayDetails() {
System.out.println("Name: " +
name); System.out.println("Age: " +
age);
}
}
// Derived class Student
class Student extends Person {
// Additional attribute
private String
studentID;
// Constructor
public Student(String name, int age, String studentID) {
super(name, age);
this.studentID = studentID;
}
// Method to display details
@Override
public void displayDetails() {
super.displayDetails(); // Call the displayDetails method from Person
System.out.println("Student ID: " + studentID);
}
}
// Main class to test the
implementation public class
PersonMain {
public static void main(String[] args) {
// Create a Person object
Person person = new Person("Alice",
30); System.out.println("Person
Details:"); person.displayDetails();
// Create a Student object
Student student = new Student("Bob", 20, "S123456");
System.out.println("\nStudent Details:");
student.displayDetails();
}
}
Output:-
Person Details:
Name: Alice
Age: 30
Student Details:
Name: Bob
Age: 20
Student ID: S123456
18) Write a Java program to perform division of two numbers and handle the ArithmeticException if
the denominator is zero.
Ans :-
import java.util.Scanner;
public class DivisionHandling {
public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
// Prompt the user to enter the
numerator System.out.print("Enter the
numerator: "); int numerator =
scanner.nextInt();
// Prompt the user to enter the
denominator System.out.print("Enter the
denominator: "); int denominator =
scanner.nextInt();
try {
// Perform the division
int result = divide(numerator,
denominator); System.out.println("Result: "
+ result);
} catch (ArithmeticException e) {
// Handle the ArithmeticException
System.out.println("Error: Division by zero is not allowed.");
}
scanner.close();
}
// Method to perform division
public static int divide(int num, int den) throws ArithmeticException {
return num / den;
}
}
Output:-
Enter the numerator: 4
Enter the denominator: 0
Error: Division by zero is not allowed.
19) Create a simple calculator using Java Swing that can perform basic arithmetic operations.
Ans:-
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SwingCalculator extends JFrame implements ActionListener {
private JTextField display;
private double num1, num2,
result; private char operator;
public SwingCalculator() {
// Create frame
JFrame frame = new JFrame("Swing Calculator");
frame.setSize(400, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create display field
display = new JTextField();
display.setFont(new Font("Arial", Font.PLAIN, 24));
display.setHorizontalAlignment(JTextField.RIGHT);
display.setEditable(false);
// Create panel for buttons
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4, 10, 10));
// Define button labels
String[] buttonLabels =
{
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", "C", "=", "+"
};
// Create buttons and add to
panel for (String label :
buttonLabels) {
JButton button = new JButton(label);
button.setFont(new Font("Arial", Font.PLAIN, 24));
button.addActionListener(this);
panel.add(button);
}
// Add components to frame
frame.add(display, BorderLayout.NORTH);
frame.add(panel);
// Set frame visibility
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if ((command.charAt(0) >= '0' && command.charAt(0) <= '9') || command.equals(".")) {
display.setText(display.getText() + command);
} else if (command.equals("C")) {
display.setText("");
num1 = num2 = result = 0;
} else if (command.equals("=")) {
num2 = Double.parseDouble(display.getText());
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
}
display.setText(String.valueOf(result));
num1 = result;
} else {
if (display.getText().isEmpty()) return;
num1 = Double.parseDouble(display.getText());
operator = command.charAt(0);
display.setText("");
}
}
public static void main(String[] args) {
new SwingCalculator();
}
}