[Go to site: main page, start]

0% found this document useful (0 votes)
5 views70 pages

Java Programming Lab

The document contains multiple Java programs demonstrating various functionalities including prime number generation, matrix multiplication, text file analysis, random number generation, string manipulation, and multi-threading. Each section includes code snippets, user input prompts, and expected outputs. The programs cover fundamental concepts of Java programming and showcase practical applications of algorithms and data structures.

Uploaded by

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

Java Programming Lab

The document contains multiple Java programs demonstrating various functionalities including prime number generation, matrix multiplication, text file analysis, random number generation, string manipulation, and multi-threading. Each section includes code snippets, user input prompts, and expected outputs. The programs cover fundamental concepts of Java programming and showcase practical applications of algorithms and data structures.

Uploaded by

rajiv gandhi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PRIME NUMBERS UP TO INTEGER

import [Link];
public class PrimeNumbers
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
[Link]("Enter an integer: ");
int n = [Link]();
[Link]("Prime numbers up to " + n + ":");
for (int i = 2;i<= n;i++)
{
if (isPrime(i))
{
[Link](i + " ");
}
}
[Link]();
}
public static Boolean isPrime(int num)
{
if (num<= 1) return false;
for (int i = 2; i<= [Link](num); i++)
{
if (num % i == 0)
return false;
}
return true;
}
}
Output:
Enter an integer: 20
Prime numbers up to 20:
2 3 5 7 11 13 17 19
MATRIX MULTIPLICATION

import [Link];
public class MatrixMultiplication
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
[Link]("Enter the number of rows for the first matrix: ");
int rows1 = [Link]();
[Link]("Enter the number of columns for the first matrix: ");
int cols1 = [Link]();
[Link]("Enter the number of rows for the second matrix: ");
int rows2 = [Link]();
[Link]("Enter the number of columns for the second matrix: ");
int cols2 = [Link]();
if (cols1 != rows2)
{
[Link]("Matrix multiplication is not possible. Columns of the first matrix must equal
rows of the second matrix.");
return;
}
int[][] matrix1 = new int[rows1][cols1];
[Link]("Enter elements of the first matrix:");
for (int i = 0; i< rows1; i++)
{
for (int j = 0; j < cols1; j++)
{
[Link]("Element [" + i + "][" + j + "]: ");
matrix1[i][j] = [Link]();
}
}
int[][] matrix2 = new int[rows2][cols2];
[Link]("Enter elements of the second matrix:");
for (int i = 0; i< rows2; i++)
{
for (int j = 0; j < cols2; j++)
{
[Link]("Element [" + i + "][" + j + "]: ");
matrix2[i][j] = [Link]();
}
}
int[][] result = new int[rows1][cols2];
for (inti = 0; i< rows1; i++)
{
for (int j = 0; j < cols2; j++)
{
for (int k = 0; k < cols1; k++)
{
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
[Link]("Resultant Matrix:");
for (inti = 0; i< rows1; i++)
{
for (int j = 0; j < cols2; j++)
{
[Link](result[i][j] + " ");
}
[Link]();
}
[Link]();
}
}
Output:
Enter the number of rows for the first matrix: 2
Enter the number of columns for the first matrix: 3
Enter the number of rows for the second matrix: 3
Enter the number of columns for the second matrix: 2
Enter elements of the first matrix:
Element [0][0]: 1
Element [0][1]: 2
Element [0][2]: 3
Element [1][0]: 4
Element [1][1]: 5
Element [1][2]: 6
Enter elements of the second matrix:
Element [0][0]: 7
Element [0][1]: 8
Element [1][0]: 9
Element [1][1]: 10
Element [2][0]: 11
Element [2][1]: 12

Resultant Matrix:
58 64
139 154
TEXT FILE ANALYZER USING GUI
import [Link];
public class TextStatistics
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
[Link]("Enter text (type 'exit' on a new line to finish):");
int lineCount = 0;
int wordCount = 0;
int charCount = 0;
while (true)
{
String line = [Link]();
if ([Link]("exit"))
{
break;
}
lineCount++;
charCount += [Link]();
String[] words = [Link]().split("\\s+");
wordCount += [Link];
}
[Link]("\nText Statistics:");
[Link]("Number of lines: " + lineCount);
[Link]("Number of words: " + wordCount);
[Link]("Number of characters (including spaces): " + charCount);
[Link]();
}
}
Output:
Enter text (type 'exit' on a new line to finish):
Hello World!
This is a test.
Java programming is fun.
Exit

Text Statistics:
Number of lines: 3
Number of words: 10
Number of characters (including spaces): 51
GENERATING RANDOM NUMBERS WITH RANGE-BASED OUTPUT
import [Link];
import [Link];
public class RandomNumberRange
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
Random random = new Random();
[Link]("Enter the lower limit: ");
int lowerLimit = [Link]();
[Link]("Enter the upper limit: ");
int upperLimit = [Link]();
if (lowerLimit>upperLimit)
{
[Link]("Invalid input: Lower limit should be less than or equal to the upper limit.");
return;
}
int randomNumber = [Link]((upperLimit - lowerLimit) + 1) + lowerLimit;
[Link]("Generated Random Number: " + randomNumber);
if (randomNumber< (lowerLimit + upperLimit) / 2)
{
[Link]("The number is in the lower half of the range.");
}
else
{
[Link]("The number is in the upper half of the range.");
}
[Link]();
}
}
Output:
Enter the lower limit: 10
Enter the upper limit: 50
Generated Random Number: 27
The number is in the lower half of the range.
STRING MANIPULATION USING CHARACTERARRAY

a. String length
import [Link];
public class StringLength
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();
char[]charArray = [Link]();
[Link]("Length of the string: " + [Link]);
[Link]();
}
}
Output:

Enter a string: HelloWorld

Length of the string: 10


b. Finding a character at a particular position
import [Link];
public class CharacterAtPosition
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();
char[] charArray = [Link]();
[Link]("Enter a position to find the character (0-based index): ");
int position = [Link]();
if (position >= 0 && position <[Link])
{
[Link]("Character at position " + position + ": " + charArray[position]);
}
else
{
[Link]("Invalid position!");
}
[Link]();
}
}
Output:
Enter a string: helloworld
Enter a position to find the character(0-based index): 5

Character at position 5: w
c. Concatenating two strings
import [Link];
public class StringConcatenation {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the first string: ");
String str1 = [Link]();
[Link]("Enter the second string: ");
String str2 = [Link]();
char[] charArray1 = [Link]();
char[] charArray2 = [Link]();
char[] concatenatedArray = new char[[Link] + [Link]];
[Link](charArray1, 0, concatenatedArray, 0, [Link]);
[Link](charArray2, 0, concatenatedArray, [Link], [Link]);
[Link]("Concatenated string: " + new String(concatenatedArray));
[Link]();
}
}
Output:
Input:
Enter the first string: Hello
Enter the second string: World
Output:
Concatenated string: HelloWorld
STRING MANIPULATION IN JAVA
a. String Concatenation
import [Link];
public class StringConcatenation
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
[Link]("Enter the first string: ");
String str1 = [Link]();
[Link]("Enter the second string: ");
String str2 = [Link]();
String concatenatedString = str1 + str2;
[Link]("Concatenated string: " + concatenatedString);
[Link]();
}
}
OUTPUT
Enter the first string: Hello
Enter the second string: World
o/p
Concatenated string: HelloWorld
b. Search a substring
import [Link];
public class SubstringSearch
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
[Link]("Enter the main string: ");
String mainString = [Link]();
[Link]("Enter the substring to search: ");
String subString = [Link]();
if ([Link](subString)) {
[Link]("Substring found at index: " + [Link](subString));
}
else
{
[Link]("Substring not found!");
}
[Link]();
}
}
Output:
Enter the main string: HelloWorld
Enter the substring to search: World
o/p
Substring found at index: 5
c. To extract substring from given string
import [Link];
public class ExtractSubstring
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
[Link]("Enter the main string: ");
String mainString = [Link]();
[Link]("Enter the starting index: ");
int startIndex = [Link]();
[Link]("Enter the ending index (exclusive): ");
int endIndex = [Link]();
try
{
String substring = [Link](startIndex, endIndex);
[Link]("Extracted substring: " + substring);
}
catch (StringIndexOutOfBoundsException e)
{
[Link]("Invalid indices! Please ensure they are within the string's bounds.");
}
catch (IllegalArgumentException e) {
[Link]("Start index must be less than end index!");
}
[Link]();
}
}
Output:
Enter the main string: JavaProgramming
Enter the starting index: 5
Enter the ending index (exclusive): 15
o/p
Extracted substring: Programming
STRING OPERATIONS USING STRING BUFFER CLASS
a. Length of a string
import [Link];
public class StringBufferOperations {
public static void main(String[] args) {
StringBufferstringBuffer = new StringBuffer();
Scanner scanner = new Scanner([Link]);
[Link]("Enter a string: ");
String userInput = [Link]();
[Link](userInput);
int length = [Link]();
[Link]("The length of the string is: " + length);
[Link]();
}
}
OUTPUT:
Enter a string: Eclipse IDE
The length of the string is: 11
b. Reverse a string
import [Link];
public class ReverseStringBuffer {
public static void main(String[] args) {
StringBufferstringBuffer = new StringBuffer();
Scanner scanner = new Scanner([Link]);
[Link]("Enter a string to reverse: ");
String userInput = [Link]();
[Link](userInput);
StringBufferreversedString = [Link]();
[Link]("The reversed string is: " + reversedString);
[Link]();
}
}
OUTPUT:
Enter a string to reverse: Hello, World!
The reversed string is: !dlroW ,olleH
c. Delete a substring from the given string
import [Link];
public class DeleteSubstring {
public static void main(String[] args) {
StringBufferstringBuffer = new StringBuffer();
Scanner scanner = new Scanner([Link]);
[Link]("Enter the original string: ");
String userInput = [Link]()
[Link](userInput);
[Link]("Enter the starting index of the substring to delete: ");
int startIndex = [Link]();
[Link]("Enter the ending index of the substring to delete: ");
int endIndex = [Link]();
if (startIndex< 0 || endIndex>[Link]() || startIndex>= endIndex) {
[Link]("Invalid indices. Please try again.");
} else {
[Link](startIndex, endIndex);
[Link]("The updated string after deletion is: " + stringBuffer);
}
[Link]();
}
}
OUTPUT:
Enter the original string: Hello, World!
Enter the starting index of the substring to delete: 7
Enter the ending index of the substring to delete: 12
The updated string after deletion is: Hello, !
MULTI-THREAD
import [Link];
class RandomNumberGenerator extends Thread {
public static int number = 0;
@Override
public void run() {
Random random = new Random();
try {
while (true) {
number = [Link](100) + 1;
[Link]("Generated Number: " + number);
[Link](1000);
}
} catch (InterruptedException e) {
[Link]("RandomNumberGenerator interrupted");
}
}
}
classSquareCalculator extends Thread {
@Override
public void run() {
try {
while (true) {
if ([Link] % 2 == 0 &&[Link] != 0) {
int square = [Link] * [Link];
[Link]("Square of " + [Link] + " is: " + square);
}
[Link](1000);
}
} catch (InterruptedException e) {
[Link]("SquareCalculator interrupted");
}
}
}
classCubeCalculator extends Thread {
@Override
public void run() {
try {
while (true) {
if ([Link] % 2 != 0) {
int cube = [Link] * [Link] *
[Link];
[Link]("Cube of " + [Link] + " is: " + cube);
}
[Link](1000);
}
} catch (InterruptedException e) {
[Link]("CubeCalculator interrupted");
}
}
}
public class MultiThreadedApplication {
public static void main(String[] args) {
RandomNumberGeneratorrngThread = new RandomNumberGenerator();
SquareCalculatorsquareThread = new SquareCalculator();
CubeCalculatorcubeThread = new CubeCalculator();
[Link]();
[Link]();
[Link]();
}
}
OUTPUT:
Generated Number: 8
Square of 8 is: 64
Generated Number: 15
Cube of 15 is: 3375
Generated Number: 2
Square of 2 is: 4
Generated Number: 7
Cube of 7 is: 343
PRINT THE NUMBERS USING THREAD
import [Link];
class NumberPrinter extends Thread {
private int start;
private int end;
public NumberPrinter(int start, int end) {
[Link] = start;
[Link] = end;
}
@Override
public void run() {
for (inti = start; i<= end; i++) {
[Link]([Link]().getName() + " - Number: " + i);
try {
[Link](500);
} catch (InterruptedException e) {
[Link]([Link]().getName() + " interrupted");
}
}
}
}

public class MultiThreadedNumberPrinting {


public static void main(String[] args) {
NumberPrinter thread1 = new NumberPrinter(1, 10);
NumberPrinter thread2 = new NumberPrinter(90, 100);
[Link]("Thread1");
[Link]("Thread2");
[Link]();
[Link]();
}
}
OUTPUT:
Thread1 - Number: 1
Thread2 - Number: 90
Thread1 - Number: 2
Thread2 - Number: 91
Thread1 - Number: 3
Thread2 - Number: 92
Thread1 - Number: 4
Thread2 - Number: 93
Thread1 - Number: 5
Thread2 - Number: 94
Thread1 - Number: 6
Thread2 - Number: 95
Thread1 - Number: 7
Thread2 - Number: 96
Thread1 - Number: 8
Thread2 - Number: 97
Thread1 - Number: 9
Thread2 - Number: 98
Thread1 - Number: 10
Thread2 - Number: 99
Thread2 - Number: 100
HANDLING BASIC JAVA EXCEPTIONS
a. Arithmetic Exception
import [Link];
public class ArithmeticExceptionDemo {
public static void main(String[] args) {
int numerator = 10;
int denominator = 0;
try {
int result = numerator / denominator;
[Link]("The result is: " + result);
} catch (ArithmeticException e)
[Link]("ArithmeticException caught: Division by zero is not allowed.");
} finally {
[Link]("Execution completed.");
}
}
}
OUTPUT:
The result is: 5
Execution completed.

ArithmeticException caught: Division by zero is not allowed.


Execution completed.
b. Number Format Exception
import [Link];
public class NumberFormatExceptionDemo {
public static void main(String[] args) {
String invalidNumber = "abc";
String validNumber = "123";
try {
int result = [Link](invalidNumber);
[Link]("The converted number is: " + result);
} catch (NumberFormatException e) {
[Link]("NumberFormatException caught: Cannot convert '"
+ invalidNumber + "' to a number.");
}
try {
int validResult = [Link](validNumber);
[Link]("The converted valid number is: " + validResult);
} catch (NumberFormatException e) {
[Link]("This block will not execute for a valid number.");
}

[Link]("Program execution completed.");


}
}
OUTPUT:
NumberFormatException caught: Cannot convert 'abc' to a number.
The converted valid number is: 123
Program execution completed.
C. ArrayIndexOutofBoundException
import [Link];
import [Link];
import [Link];
public class ArrayIndexOutOfBoundsWithFile {
public static void main(String[] args) {
int[] numbers = new int[5];
try {
File file = new File("[Link]");
Scanner scanner = new Scanner(file);
int index = 0;
while ([Link]() && index <[Link]) {
numbers[index++] = [Link]();
}
[Link]();
} catch (FileNotFoundException e) {
[Link]("File not found: " + [Link]());
return;
}
try {
[Link]("Accessing element at index 5: " + numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Exception caught: " + [Link]());
[Link]("You tried to access an index outside the array's bounds.");
}
[Link]("Accessing element at index 2: " + numbers[2]);
}
}
OUTPUT:
Exception caught: Index 5 out of bounds for length 5
You tried to access an index outside the array's bounds.
Accessing element at index 2: 30
d. NegativeArraySizeException
import [Link];
public class NegativeArraySizeExample {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
try {
[Link]("Enter the size of the array: ");
int size = [Link]();
int[] array = new int[size];
[Link]("Array of size " + size + " created successfully.");
} catch (NegativeArraySizeException e) {
[Link]("Exception caught: " + [Link]());
[Link]("Array size cannot be negative.");
}
[Link]();
}
}
OUTPUT:
Enter the size of the array: -5
Exception caught: -5
Array size cannot be negative.
FILE ANALYSIS TOOL USING JAVA

import [Link];
import [Link];
public class FileInfo {
public static void main(String[] args) {
// Create a scanner object to read user input
Scanner scanner = new Scanner([Link]);

// Prompt the user to enter the file name


[Link]("Enter the file name: ");
String fileName = [Link]();

// Create a File object using the file name provided by the user
File file = new File(fileName);

// Check if the file exists


if ([Link]()) {
[Link]("File exists: Yes");

// Check if the file is readable


if ([Link]()) {
[Link]("File is readable: Yes");
} else {
[Link]("File is readable: No");
}
// Check if the file is writable
if ([Link]()) {
[Link]("File is writable: Yes");
} else {
[Link]("File is writable: No");
}
// Display the type of the file (file or directory)
if ([Link]()) {
[Link]("The file is a regular file.");
} else if ([Link]()) {
[Link]("The file is a directory.");
} else {
[Link]("The file is neither a regular file nor a directory.");
}
// Display the length of the file in bytes
[Link]("File size: " + [Link]() + " bytes");
} else {
[Link]("The file does not exist.");
}
// Close the scanner object
[Link]();
}
}
OUTPUT:
Enter the file name: [Link]
File exists: Yes
File is readable: Yes
File is writable: Yes
The file is a regular file.
File size: 16 bytes
FRAMES AND CONTROLS
import [Link].*;
import [Link].*;
import [Link];
import [Link];
public class TextFormatter {
public static void main(String[] args) {
JFrame frame = new JFrame("Text Formatter");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](500, 400);
[Link](new BorderLayout());
JPanel controlPanel = new JPanel();
[Link](new GridLayout(3, 2));
JLabel sizeLabel = new JLabel("Font Size:");
JTextField sizeField = new JTextField("12");
[Link](sizeLabel);
[Link](sizeField);
JLabel familyLabel = new JLabel("Font Family:");
String[] fontFamilies = {"Arial", "Times New Roman", "Courier", "Helvetica"};
JComboBox<String> familyComboBox = new JComboBox<>(fontFamilies);
[Link](familyLabel);
[Link](familyComboBox);
JCheckBox boldCheckBox = new JCheckBox("Bold");
JCheckBox italicCheckBox = new JCheckBox("Italic");
[Link](boldCheckBox);
[Link](italicCheckBox);
// Text area to display the formatted text
JTextArea textArea = new JTextArea();
[Link](new Font("Arial", [Link], 12)); // Default font
JScrollPane scrollPane = new JScrollPane(textArea);

// Button to apply changes


JButton applyButton = new JButton("Apply");

// Add action listener to apply button


// Declare the variables as final to avoid compilation errors
final JTextField finalSizeField = sizeField;
final JComboBox<String> finalFamilyComboBox = familyComboBox;
final JCheckBox finalBoldCheckBox = boldCheckBox;
final JCheckBox finalItalicCheckBox = italicCheckBox;
final JTextArea finalTextArea = textArea;

[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Get the font size, family, and style
int fontSize = [Link]([Link]());
String fontFamily = (String) [Link]();
int fontStyle = [Link];

// Adjust font style based on checkboxes


if ([Link]() && [Link]()) {
fontStyle = [Link] | [Link];
} else if ([Link]()) {
fontStyle = [Link];
} else if ([Link]()) {
fontStyle = [Link];
}

// Set the new font to the text area


[Link](new Font(fontFamily, fontStyle, fontSize));
}
});

// Add components to the frame


[Link](controlPanel, [Link]);
[Link](scrollPane, [Link]);
[Link](applyButton, [Link]);

// Display the frame


[Link](true);
}
}
OUTPUT:
MOUSE EVENT HANDLING
import [Link].*;
import [Link].*;

public class MouseEventDemo extends Frame {

private String eventName = "";

// Constructor to set up the frame


public MouseEventDemo() {
setTitle("Mouse Event Demo");
setSize(500, 500);
setVisible(true);

// Add MouseAdapter to handle mouse events


addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
eventName = "Mouse Clicked";
repaint();
}

@Override
public void mousePressed(MouseEvent e) {
eventName = "Mouse Pressed";
repaint();
}
@Override
public void mouseReleased(MouseEvent e) {
eventName = "Mouse Released";
repaint();
}

@Override
public void mouseEntered(MouseEvent e) {
eventName = "Mouse Entered";
repaint();
}

@Override
public void mouseExited(MouseEvent e) {
eventName = "Mouse Exited";
repaint();
}
});

addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
eventName = "Mouse Dragged";
repaint();
}

@Override
public void mouseMoved(MouseEvent e) {
eventName = "Mouse Moved";
repaint();
}
});

// Add window listener to close the window


addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
[Link](0);
}
});
}

// Method to paint the event name in the center


@Override
public void paint(Graphics g) {
[Link](g);
Font font = new Font("Arial", [Link], 20);
[Link](font);
FontMetrics fm = [Link]();
int width = [Link](eventName);
int height = [Link]();
int x = (getWidth() - width) / 2;
int y = (getHeight() + height) / 2;
[Link](eventName, x, y);
}
// Main method to run the application
public static void main(String[] args) {
new MouseEventDemo();
}
}
OUTPUT:
CALCULATOR
import [Link].*;
import [Link].*;

public class SimpleCalculator extends Frame {

private TextField display;


private String currentInput = ""; // Stores the current input
private String previousInput = ""; // Stores the previous input for operations
private String operator = ""; // Stores the operator (+, -, *, /, %)

// Constructor to set up the frame


public SimpleCalculator() {
setTitle("Simple Calculator");
setSize(400, 500);
setLayout(new BorderLayout());

// Create the text field for display


display = new TextField();
[Link](new Font("Arial", [Link], 24));
[Link](false);
add(display, [Link]);

// Create the panel for buttons


Panel panel = new Panel();
[Link](new GridLayout(5, 4)); // Grid layout with 5 rows and 4 columns
// Define the button labels
String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+",
"C", "%", "Exit", "Clear"
};

// Create and add buttons to the panel


for (String label : buttons) {
Button button = new Button(label);
[Link](new Font("Arial", [Link], 20));
[Link](new ButtonClickListener());
[Link](button);
}

// Add the button panel to the frame


add(panel, [Link]);

// Add window listener to handle closing


addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
[Link](0);
}
});
setVisible(true);
}

// Inner class to handle button clicks


private class ButtonClickListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String buttonText = [Link]();

// Handle numeric and decimal inputs


if ([Link]("[0-9]") || [Link](".")) {
currentInput += buttonText;
[Link](currentInput);
}
// Handle operators
else if ([Link]("+") || [Link]("-") ||
[Link]("*") || [Link]("/") ||
[Link]("%")) {
if (![Link]()) {
previousInput = currentInput;
currentInput = "";
operator = buttonText;
}
}
// Handle equals (=) to calculate the result
else if ([Link]("=")) {
try {
double num1 = [Link](previousInput);
double num2 = [Link](currentInput);
double result = 0;

switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 == 0) {
[Link]("Error: Div by Zero");
return;
} else {
result = num1 / num2;
}
break;
case "%":
result = num1 % num2;
break;
}
[Link]([Link](result));
currentInput = [Link](result);
previousInput = "";
operator = "";
} catch (NumberFormatException ex) {
[Link]("Error");
}
}
// Handle clear (C) button
else if ([Link]("C")) {
currentInput = "";
previousInput = "";
operator = "";
[Link]("");
}
// Handle Exit button
else if ([Link]("Exit")) {
[Link](0);
}
// Handle Clear button
else if ([Link]("Clear")) {
currentInput = "";
[Link]("");
}
}
}

// Main method to run the calculator


public static void main(String[] args) {
new SimpleCalculator();
}
}
OUTPUT:
TRAFFIC LIGHT SIMULATOR
import [Link].*;
import [Link].*;
import [Link].*;

public class TrafficLightSimulator extends JFrame {

private JLabel messageLabel;


private JRadioButton redButton, yellowButton, greenButton;
private ButtonGroup buttonGroup;

// Constructor to set up the frame


public TrafficLightSimulator() {
setTitle("Traffic Light Simulator");
setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());

// Initialize message label


messageLabel = new JLabel();
[Link](new Font("Arial", [Link], 20));
add(messageLabel);

// Create radio buttons


redButton = new JRadioButton("Red");
yellowButton = new JRadioButton("Yellow");
greenButton = new JRadioButton("Green");
// Create a ButtonGroup to ensure only one radio button can be selected at a time
buttonGroup = new ButtonGroup();
[Link](redButton);
[Link](yellowButton);
[Link](greenButton);

// Add the radio buttons to the frame


add(redButton);
add(yellowButton);
add(greenButton);

// Add action listeners to the radio buttons


[Link](new LightSelectionListener());
[Link](new LightSelectionListener());
[Link](new LightSelectionListener());

// Set the frame to be visible


setVisible(true);
}

// ActionListener for handling the radio button selection


private class LightSelectionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if ([Link]()) {
[Link]("Stop");
[Link]([Link]);
} else if ([Link]()) {
[Link]("Ready");
[Link]([Link]);
} else if ([Link]()) {
[Link]("Go");
[Link]([Link]);
}
}
}

// Main method to run the program


public static void main(String[] args) {
new TrafficLightSimulator();
}
}
OUTPUT:

You might also like