0% found this document useful (0 votes)
2 views47 pages

II Cs Java Programming

The document outlines multiple Java programs, each with a specific aim and procedure. Programs include generating prime numbers, multiplying matrices, counting text statistics, generating random numbers, and performing various string manipulations. Each program follows a structured approach, detailing steps for user input, processing, and output display.

Uploaded by

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

II Cs Java Programming

The document outlines multiple Java programs, each with a specific aim and procedure. Programs include generating prime numbers, multiplying matrices, counting text statistics, generating random numbers, and performing various string manipulations. Each program follows a structured approach, detailing steps for user input, processing, and output display.

Uploaded by

then mozhi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 47

PRIME NUMBER

AIM
To Write a Java program that prompts the user for an integer and then prints out all
the prime numbers up to that Integer.

PROCEDURE
Step 1: Import the Scanner Class The program starts by importing the
`java.util.Scanner` class, which allows the program to read input from the user.
Step 2: Create a Scanner Object A `Scanner` object named `scanner` is created to
read the user's input.
Step 3: Prompt the User for Input.
Step 4: Read the User's Input the user's input is read using `int number =
scanner.nextInt()` and stored in the `number` variable.
Step 5: The program prints the prime numbers up to the input number using a `for`
loop.
Step 6: The `isPrime` method checks if a number is prime by iterating from 2 to
the square root of the number and checking for divisibility.
Step 7: Print the Prime Number
Step 8: The program repeats steps 5-7 until all prime numbers up to the input
number have been printed.
1. Prime.java
import java.util.Scanner;
public class Prime {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = scanner.nextInt();
System.out.println("Prime numbers up to " + number + ":");
for (int i = 2; i <= number; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
}
public static boolean isPrime(int num) {
if (num < 2) return false;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
OUTPUT
AIM
To Write a Java program to multiply two given matrices.
PROCEDURE
Step 1: The program starts by importing the `java.util.Scanner` class.

Step 2: Create a Scanner Object.

Step 3: The program prompts the user to enter the number of rows and
columns for the first and second matrices.

Step 4: The user's input is read using `scanner.nextInt()` and stored in the
`rows1`, `cols1`, `rows2`, and `cols2 variables.

Step 5: The program checks if the number of columns in the first matrix is
equal to the number of rows in the second matrix. If not, it prints an error message
and exits.

Step 6: Three 2D integer arrays `matrix1`, `matrix2`, and `result` are


declared to store the elements of the first matrix, second matrix, and result matrix
respectively.

Step 7: Read Matrix Elements.


Step 8: The program performs matrix multiplication using three nested
loops.

Step 9: The program prints the elements of the result matrix.

2.Matrix.java
import java.util.Scanner;

public class Matrix {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter rows and columns for the first matrix: ");


int rows1 = scanner.nextInt();
int cols1 = scanner.nextInt();
System.out.print("Enter rows and columns for the second matrix: ");
int rows2 = scanner.nextInt();
int cols2 = scanner.nextInt();

if (cols1 != rows2) {
System.out.println("Matrix multiplication is not possible.");
return;
}

int[][] matrix1 = new int[rows1][cols1];


int[][] matrix2 = new int[rows2][cols2];
int[][] result = new int[rows1][cols2];
System.out.println("Enter elements of the first matrix:");
for (int i = 0; i < rows1; i++)
for (int j = 0; j < cols1; j++)
matrix1[i][j] = scanner.nextInt();

System.out.println("Enter elements of the second matrix:");


for (int i = 0; i < rows2; i++)
for (int j = 0; j < cols2; j++)
matrix2[i][j] = scanner.nextInt();

for (int i = 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];

System.out.println("Resultant Matrix:");
for (int[] row : result) {
for (int val : row) {
System.out.print(val + " ");
}
System.out.println();
}

scanner.close();
}
}

AIM
Write a Java program that displays the number of characters, lines and
Words in a text

PROCEDURE

Step 1: Import the `java.util.Scanner` class.

Step 2: Create a `Scanner` object to read user input.

Step 3: Prompt the user to enter their text.

Step 4: Initialize counters for characters, words, and lines.

Step 5: Read the text line by line using a `while` loop.


Step 6: Update the counters for characters, words, and lines for each line.

Step 7: Print the text statistics, including lines, words, and characters.

Step 8: Close the `Scanner` object.

3. Text.java
import java.util.Scanner;
public class Text {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Enter your text :");

int characterCount = 0;
int wordCount = 0;
int lineCount = 0;

while (true) {
String line = scanner.nextLine();

if (line.isEmpty()) {
break;
}

lineCount++;
characterCount += line.replace(" ", "").length();
wordCount += line.trim().split("\\s+").length;
}

System.out.println("\nText Statistics:");
System.out.println("Number of lines: " + lineCount);
System.out.println("Number of words: " + wordCount);
System.out.println("Number of characters (excluding spaces): " +
characterCount);

scanner.close();
}
}

AIM
Generate random numbers between two given limits using Random class
and print messages according to the range of the value generated.
PROCEDURE
Step 1: Import Necessary Classes
Step 2: Create a `Scanner` object to read user input.

Step 3: Prompt user to enter lower and upper limits.

Step 4: Check if lower limit is less than or equal to upper limit.

Step 5: Generate a random number within the specified range.

Step 6: Determine if the random number is in the lower, middle, or upper


range.

Step 7: Print the generated random number and its range.

Step 8: Close the `Scanner` object.


4. Message.java
import java.util.Random;
import java.util.Scanner;

public class Message {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the lower limit: ");


int lowerLimit = scanner.nextInt();

System.out.print("Enter the upper limit: ");


int upperLimit = scanner.nextInt();
if (lowerLimit > upperLimit) {
System.out.println("Invalid range. The lower limit must be less than
or equal to the upper limit.");
return;
}

Random random = new Random();


int randomNumber = random.nextInt(upperLimit - lowerLimit + 1) +
lowerLimit;

System.out.println("Generated random number: " + randomNumber);

if (randomNumber < (lowerLimit + upperLimit) / 3) {


System.out.println("The number is in the lower range.");
} else if (randomNumber < 2 * (lowerLimit + upperLimit) / 3) {
System.out.println("The number is in the middle range.");
} else {
System.out.println("The number is in the upper range.");
}

scanner.close();
}
}
AIM
To Write a program to do String Manipulation using CharacterArray and
perform the following string operations:
a. String length
b. Finding a character at a particular position
c. Concatenating two strings
PROCEDURE
1. Import `java.util.Scanner` class.
2. Create a `Scanner` object to read user input.
3. Prompt user to enter the first string.
4. Convert the string to a character array and find its length.
5. Prompt user to enter a position to find a character.
6. Check if the position is valid and print the character at that position.
7. Prompt user to enter the second string.
8. Concatenate the two strings using character arrays.
9. Print the concatenated string.
10. Close the `Scanner` object.
5.StrManipulation.java
import java.util.Scanner;
public class StrManipulation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the first string: ");


String str1 = scanner.nextLine();
char[] charArray1 = str1.toCharArray();

int length1 = charArray1.length;


System.out.println("Length of the first string: " + length1);

System.out.print("Enter the position to find the character (1-based


index): ");
int position = scanner.nextInt();
scanner.nextLine();

if (position > 0 && position <= length1) {


System.out.println("Character at position " + position + ": " +
charArray1[position - 1]);
} else {
System.out.println("Invalid position!");
}

System.out.print("Enter the second string: ");


String str2 = scanner.nextLine();
char[] charArray2 = str2.toCharArray();
char[] concatenatedArray = new char[charArray1.length +
charArray2.length];
System.arraycopy(charArray1, 0, concatenatedArray, 0,
charArray1.length);
System.arraycopy(charArray2, 0, concatenatedArray,
charArray1.length, charArray2.length);

String concatenatedString = new String(concatenatedArray);


System.out.println("Concatenated string: " + concatenatedString);

scanner.close();
}
}

AIM
Write a program to perform the following string operations using String
class:
a. String Concatenation
b. Search a substring
c. To extract substring from given string
PROCEDURE
1. Import `java.util.Scanner` class.
2. Create a `Scanner` object to read user input.
3. Prompt user to enter two strings.
4. Concatenate the two strings.
5. Print the concatenated string.
6. Prompt user to enter a substring to search for.
7. Check if the first string contains the substring.
8. Print the result of the substring search.
9. Prompt user to enter start and end indices to extract a substring.
10. Extract the substring using the provided indices.
11. Print the extracted substring or an error message if indices are invalid.
12. Close the `Scanner` object.

6. StrOperation.java
import java.util.Scanner;

public class StrOperation {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the first string: ");


String str1 = scanner.nextLine();

System.out.print("Enter the second string: ");


String str2 = scanner.nextLine();

String concatenatedString = str1 + str2;


System.out.println("Concatenated string: " + concatenatedString);
System.out.print("Enter the substring to search for: ");
String substringToSearch = scanner.nextLine();
if (str1.contains(substringToSearch)) {
System.out.println("The substring \"" + substringToSearch + "\" is
found in the first string.");
} else {
System.out.println("The substring \"" + substringToSearch + "\" is
not found in the first string.");
}

System.out.print("Enter the start index to extract substring: ");


int startIndex = scanner.nextInt();
System.out.print("Enter the end index to extract substring: ");
int endIndex = scanner.nextInt();

if (startIndex >= 0 && endIndex <= str1.length() && startIndex <


endIndex) {
String extractedSubstring = str1.substring(startIndex, endIndex);
System.out.println("Extracted substring: " + extractedSubstring);
} else {
System.out.println("Invalid indices for substring extraction.");
}

scanner.close();
}
}
AIM
Write a program to perform string operations using String Buffer class:
a. Length of a string
b. Reverse a string
c. Delete a substring from the given string
PROCEDURE
1. Import `java.util.Scanner` class.
2. Create a `Scanner` object to read user input.
3. Prompt user to enter a string.
4. Create a `StringBuffer` object with the input string.
5. Calculate and print the length of the string.
6. Reverse the string using `reverse()` method.
7. Print the reversed string.
8. Prompt user to enter start and end indices to delete a substring.
9. Delete the substring using `delete()` method.
10. Print the string after deletion or an error message if indices are invalid.
11. Close the `Scanner` object.
7.StrBuffer.java
import java.util.Scanner;
public class StrBuffer {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a string: ");


StringBuffer stringBuffer = new StringBuffer(scanner.nextLine());

int length = stringBuffer.length();


System.out.println("Length of the string: " + length);

StringBuffer reversedString = new StringBuffer(stringBuffer).reverse();


System.out.println("Reversed string: " + reversedString);

System.out.print("Enter the start index to delete substring: ");


int startIndex = scanner.nextInt();
System.out.print("Enter the end index to delete substring: ");
int endIndex = scanner.nextInt();

if (startIndex >= 0 && endIndex <= stringBuffer.length() &&


startIndex < endIndex) {
stringBuffer.delete(startIndex, endIndex);
System.out.println("String after deletion: " + stringBuffer);
} else {
System.out.println("Invalid indices for substring deletion.");
}
scanner.close();
}
}

AIM
Write a java program that implements a multi-thread application that has
three threads. First thread generates random integer every 1 second and if the value
is even, second thread computes the square of the number and prints. If the value is
odd, the third thread will print the value of cube of the number.

PROCEDURE
1. Create a `RandomNumberGenerator` class that extends `Thread`.
2. Create a `NumberProcessor` class that extends `Thread`.
3. Initialize `NumberProcessor` objects for even and odd numbers.
4. Initialize a `RandomNumberGenerator` object with the even and odd
processors.
5. Start the even, odd, and random number generator threads.
6. In the `RandomNumberGenerator` thread.
7. In the `NumberProcessor` thread , Print the result.
8.ThreadApp.java
import java.util.Random;

class RandomNumberGenerator extends Thread {


private final NumberProcessor evenProcessor;
private final NumberProcessor oddProcessor;

public RandomNumberGenerator(NumberProcessor evenProcessor,


NumberProcessor oddProcessor) {
this.evenProcessor = evenProcessor;
this.oddProcessor = oddProcessor;
}

public void run() {


Random random = new Random();
while (true) {
int number = random.nextInt(100) + 1;
System.out.println("Generated number: " + number);

if (number % 2 == 0) {
evenProcessor.process(number);
} else {
oddProcessor.process(number);
}

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

class NumberProcessor extends Thread {


private final String type;
private int number;

public NumberProcessor(String type) {


this.type = type;
}

public void process(int number) {


this.number = number;
synchronized (this) {
notify();
}
}

public void run() {


while (true) {
synchronized (this) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}

if ("Even".equals(type)) {
System.out.println("Square of " + number + ": " + (number *
number));
} else {
System.out.println("Cube of " + number + ": " + (number *
number * number));
}
}
}
}
}

public class ThreadApp {


public static void main(String[] args) {
NumberProcessor evenProcessor = new NumberProcessor("Even");
NumberProcessor oddProcessor = new NumberProcessor("Odd");

RandomNumberGenerator randomNumberGenerator = new


RandomNumberGenerator(evenProcessor, oddProcessor);

evenProcessor.start();
oddProcessor.start();
randomNumberGenerator.start();
}
}

AIM
Write a threading program which uses the same method asynchronously to
print the numbers 1to10 using Thread1 and to print 90 to100 using Thread2.
PROCEDURE
1. Create a `NumberPrinter` class that implements `Runnable`.
2. Initialize `NumberPrinter` objects with start and end numbers.
3. Create `Thread` objects with the `NumberPrinter` objects.
4. Start the threads.
5. In the `NumberPrinter` class:
- Print numbers from start to end with a 500ms delay.
- Use `Thread.currentThread().getName()` to print the thread name.
9.Threads.java
class NumberPrinter implements Runnable {
private final int start;
private final int end;

public NumberPrinter(int start, int end) {


this.start = start;
this.end = end;
}

public void run() {


for (int i = start; i <= end; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public class Threads {


public static void main(String[] args) {
NumberPrinter printer1 = new NumberPrinter(1, 10);
NumberPrinter printer2 = new NumberPrinter(90, 100);
Thread thread1 = new Thread(printer1, "Thread1");
Thread thread2 = new Thread(printer2, "Thread2");

thread1.start();
thread2.start();
}
}

AIM
Write a program to demonstrate the use of following exceptions.
a. Arithmetic Exception
b. Number Format Exception
c. ArrayIndexOutofBoundException
d. NegativeArraySizeException
PROCEDURE
1. Create a `try` block to enclose code that may throw an exception.
2. Attempt to perform operations that may throw exceptions, such as:
- Division by zero (ArithmeticException)
- Parsing a non-numeric string to an integer (NumberFormatException)
- Accessing an array index out of bounds
(ArrayIndexOutOfBoundsException)
- Creating an array with a negative size (NegativeArraySizeException)
3. Create a corresponding `catch` block for each type of exception.
4. Handle the exception by printing an error message or taking alternative
action.
5. Repeat steps 1-4 for each type of exception.
10.Exception.java
public class Exception {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: " +
e.getMessage());
}

try {
int number = Integer.parseInt("ABC");
} catch (NumberFormatException e) {
System.out.println("NumberFormatException caught: " +
e.getMessage());
}

try {
int[] array = {1, 2, 3};
int value = array[5];
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException caught: " +
e.getMessage());
}

try {
int[] negativeArray = new int[-5];
} catch (NegativeArraySizeException e) {
System.out.println("NegativeArraySizeException caught: " +
e.getMessage());
}
}
}

AIM
Write a Java program that reads on file name from the user, then displays
information about whether the file exists, whether the file is readable, whether the
file is writable,the type of file and the length of the file in bytes

PROCEDURE

1. Import necessary classes: `java.io.File` and `java.util.Scanner`.


2. Create a `Scanner` object to read user input.
3. Prompt user to enter a file name with path.
4. Create a `File` object with the user-input file name.
5. Check if the file exists.
6. If the file exists:
- Check and print file readability and writability.
- Determine and print file type (directory, regular file, or unknown).
- Print file length in bytes.
7. If the file does not exist, print an error message.
8. Close the `Scanner` object.

11.FileInformation.java
import java.io.File;
import java.util.Scanner;

public class FileInformation {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the file name with path: ");
String fileName = scanner.nextLine();

File file = new File(fileName);

if (file.exists()) {
System.out.println("File exists: Yes");
System.out.println("Readable: " + (file.canRead() ? "Yes" : "No"));
System.out.println("Writable: " + (file.canWrite() ? "Yes" : "No"));

if (file.isDirectory()) {
System.out.println("File type: Directory");
} else if (file.isFile()) {
System.out.println("File type: Regular file");
} else {
System.out.println("File type: Unknown");
}

System.out.println("File length: " + file.length() + " bytes");


} else {
System.out.println("File does not exist.");
}

scanner.close();
}
}
AIM
Write a program to accept a text and change its size and font. Include bold
italic options. Use frames and controls.

PROCEDURE
1. Create a JFrame with a FlowLayout.
2. Add input field and label for user to enter text.
3. Add label to display styled text.
4. Add combo boxes for font and size selection.
5. Add radio buttons for style selection (plain, bold, italic).
6. Add apply button to apply selected style.
7. Implement ActionListener for apply button:
- Get input text, selected font, size, and style.
- Set styled text to display label.
- Update display label’s font and style.
8. Make frame visible using SwingUtilities.invokeLater.
12.TextStyleChanger.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TextStyleChanger extends JFrame implements ActionListener {


private JTextField inputTextField;
private JLabel displayLabel;
private JComboBox<String> fontComboBox;
private JComboBox<Integer> sizeComboBox;
private JRadioButton boldButton, italicButton, plainButton;

public TextStyleChanger() {
setTitle("Text Style Changer");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());

JLabel inputLabel = new JLabel("Enter Text:");


add(inputLabel);
inputTextField = new JTextField(20);
add(inputTextField);

displayLabel = new JLabel("Your styled text will appear here.");


displayLabel.setFont(new Font("Arial", Font.PLAIN, 16));
add(displayLabel);

JLabel fontLabel = new JLabel("Choose Font:");


add(fontLabel);
String[] fonts =
GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNa
mes();
fontComboBox = new JComboBox<>(fonts);
fontComboBox.setSelectedItem("Arial");
add(fontComboBox);

JLabel sizeLabel = new JLabel("Choose Size:");


add(sizeLabel);
Integer[] sizes = {12, 14, 16, 18, 20, 24, 28, 32};
sizeComboBox = new JComboBox<>(sizes);
sizeComboBox.setSelectedItem(16);
add(sizeComboBox);

JLabel styleLabel = new JLabel("Choose Style:");


add(styleLabel);
plainButton = new JRadioButton("Plain", true);
boldButton = new JRadioButton("Bold");
italicButton = new JRadioButton("Italic");
ButtonGroup styleGroup = new ButtonGroup();
styleGroup.add(plainButton);
styleGroup.add(boldButton);
styleGroup.add(italicButton);
add(plainButton);
add(boldButton);
add(italicButton);
JButton applyButton = new JButton("Apply Style");
add(applyButton);
applyButton.addActionListener(this);
}

public void actionPerformed(ActionEvent e) {


String text = inputTextField.getText();
String fontName = (String) fontComboBox.getSelectedItem();
int fontSize = (int) sizeComboBox.getSelectedItem();
int fontStyle = Font.PLAIN;

if (boldButton.isSelected()) {
fontStyle = Font.BOLD;
} else if (italicButton.isSelected()) {
fontStyle = Font.ITALIC;
}

displayLabel.setText(text);
displayLabel.setFont(new Font(fontName, fontStyle, fontSize));
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
TextStyleChanger frame = new TextStyleChanger();
frame.setVisible(true);
});
}
}

AIM
Write a Java program that handles all mouse events and shows the event
name at the center of the window when a mouse event is fired. (Use adapter
classes).

PROCEDURE
1. Create a JFrame with a BorderLayout.
2. Add a JLabel to display mouse events.
3. Implement MouseListener for mouse events:
- mouseClicked: update label text to "Mouse Clicked".
- mousePressed: update label text to "Mouse Pressed".
- mouseReleased: update label text to "Mouse Released".
- mouseEntered: update label text to "Mouse Entered".
- mouseExited: update label text to "Mouse Exited".
4. Implement MouseMotionListener for mouse motion events:
- mouseMoved: update label text to "Mouse Moved".
- mouseDragged: update label text to "Mouse Dragged".
5. Make frame visible using SwingUtilities.invokeLater.
13.MouseEventDemo.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class MouseEventDemo extends JFrame {


private JLabel eventLabel;

public MouseEventDemo() {
setTitle("Mouse Event Demo");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

eventLabel = new JLabel("Perform a mouse action!",


SwingConstants.CENTER);
eventLabel.setFont(new Font("Arial", Font.BOLD, 20));
add(eventLabel, BorderLayout.CENTER);

addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
eventLabel.setText("Mouse Clicked");
}
public void mousePressed(MouseEvent e) {
eventLabel.setText("Mouse Pressed");
}

public void mouseReleased(MouseEvent e) {


eventLabel.setText("Mouse Released");
}

public void mouseEntered(MouseEvent e) {


eventLabel.setText("Mouse Entered");
}

public void mouseExited(MouseEvent e) {


eventLabel.setText("Mouse Exited");
}
});

addMouseMotionListener(new MouseAdapter() {
public void mouseMoved(MouseEvent e) {
eventLabel.setText("Mouse Moved");
}

public void mouseDragged(MouseEvent e) {


eventLabel.setText("Mouse Dragged");
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
MouseEventDemo frame = new MouseEventDemo();
frame.setVisible(true);
});
}
}
For your understanding purpose:

 When you click inside the window: Mouse Clicked is displayed.


 When you press the mouse button: Mouse Pressed is displayed.
 When you release the mouse button: Mouse Released is displayed.
 When you move the mouse: Mouse Moved is displayed.
 When you drag the mouse: Mouse Dragged is displayed.

AIM
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.
PROCEDURE
1. Create a JFrame with a BorderLayout.
2. Add a JTextField to display calculations.
3. Create a JPanel with a GridLayout for buttons.
4. Add buttons for digits 0-9, operators (+, -, *, /), and equals.
5. Implement ActionListener for buttons:
- Handle digit buttons: append digit to display field.
- Handle operator buttons: store operator and first operand.
- Handle equals button: perform operation and display result.
- Handle clear button: reset display field and operands.
6. Perform operations using a switch statement.
7. Handle exceptions for divide by zero and invalid input.
8. Make frame visible using SwingUtilities.invokeLater.
14.SimpleCalculator.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SimpleCalculator extends JFrame implements ActionListener {


private JTextField displayField;
private double firstOperand = 0;
private String operator = "";
private boolean isOperatorClicked = false;

public SimpleCalculator() {
setTitle("Simple Calculator");
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

displayField = new JTextField();


displayField.setFont(new Font("Arial", Font.BOLD, 20));
displayField.setHorizontalAlignment(JTextField.RIGHT);
displayField.setEditable(false);
add(displayField, BorderLayout.NORTH);

JPanel buttonPanel = new JPanel();


buttonPanel.setLayout(new GridLayout(4, 4, 5, 5));
add(buttonPanel, BorderLayout.CENTER);

String[] buttonLabels = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"C", "0", "=", "+"
};

for (String label : buttonLabels) {


JButton button = new JButton(label);
button.setFont(new Font("Arial", Font.BOLD, 18));
button.addActionListener(this);
buttonPanel.add(button);
}
}

public void actionPerformed(ActionEvent e) {


String command = e.getActionCommand();

try {
if (command.matches("\\d")) {
if (isOperatorClicked) {
displayField.setText("");
isOperatorClicked = false;
}
displayField.setText(displayField.getText() + command);
} else if (command.matches("[+\\-*/]")) {
firstOperand = Double.parseDouble(displayField.getText());
operator = command;
isOperatorClicked = true;
} else if (command.equals("=")) {
double secondOperand =
Double.parseDouble(displayField.getText());
double result = performOperation(firstOperand, secondOperand,
operator);
displayField.setText(String.valueOf(result));
} else if (command.equals("C")) {
displayField.setText("");
firstOperand = 0;
operator = "";
}
} catch (ArithmeticException ex) {
displayField.setText("Error: Divide by Zero");
} catch (NumberFormatException ex) {
displayField.setText("Error: Invalid Input");
}
}

private double performOperation(double first, double second, String


operator) {
return switch (operator) {
case "+" -> first + second;
case "-" -> first - second;
case "*" -> first * second;
case "/" -> {
if (second == 0) throw new ArithmeticException("Divide by
Zero");
yield first / second;
}
default -> 0;
};
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
SimpleCalculator calculator = new SimpleCalculator();
calculator.setVisible(true);
});
}
}

AIM
Write a Java program that simulates a traffic light. The program lets the User
select one of three lights: red, yellow, or green with radio buttons. On Selecting a
button, an appropriate message with “stop” or “ready” or “go” Should appear
above the buttons in a selected color. Initially there is no Message shown.

PROCEDURE
1. Create a JFrame with a BorderLayout.
2. Add a JLabel to display traffic light messages.
3. Create a JPanel with a GridLayout for radio buttons.
4. Add radio buttons for red, yellow, and green traffic lights.
5. Group radio buttons using a ButtonGroup.
6. Implement ActionListener for radio buttons:
- Update JLabel text and color based on selected traffic light.
7. Make frame visible using SwingUtilities.invokeLater.

15.TrafficLightSimulator.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TrafficLightSimulator extends JFrame implements


ActionListener {
private JLabel messageLabel;
private JRadioButton redButton, yellowButton, greenButton;
private ButtonGroup buttonGroup;

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

messageLabel = new JLabel("", SwingConstants.CENTER);


messageLabel.setFont(new Font("Arial", Font.BOLD, 16));
add(messageLabel, BorderLayout.NORTH);

JPanel buttonPanel = new JPanel();


buttonPanel.setLayout(new GridLayout(3, 1));

redButton = new JRadioButton("Red");


yellowButton = new JRadioButton("Yellow");
greenButton = new JRadioButton("Green");

redButton.addActionListener(this);
yellowButton.addActionListener(this);
greenButton.addActionListener(this);

buttonGroup = new ButtonGroup();


buttonGroup.add(redButton);
buttonGroup.add(yellowButton);
buttonGroup.add(greenButton);

buttonPanel.add(redButton);
buttonPanel.add(yellowButton);
buttonPanel.add(greenButton);

add(buttonPanel, BorderLayout.CENTER);
}

public void actionPerformed(ActionEvent e) {


if (e.getSource() == redButton) {
messageLabel.setText("Stop");
messageLabel.setForeground(Color.RED);
} else if (e.getSource() == yellowButton) {
messageLabel.setText("Ready");
messageLabel.setForeground(Color.ORANGE);
} else if (e.getSource() == greenButton) {
messageLabel.setText("Go");
messageLabel.setForeground(Color.GREEN);
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
TrafficLightSimulator simulator = new TrafficLightSimulator();
simulator.setVisible(true);
});
}
}

You might also like