0% found this document useful (0 votes)
6 views44 pages

Java Lab Program26

The document outlines several Java programs, including algorithms and code for printing prime numbers, multiplying matrices, counting characters, lines, and words in text, generating random numbers, and performing string manipulations. Each section provides a step-by-step algorithm followed by the corresponding Java code and sample outputs. The programs demonstrate various programming concepts such as loops, conditionals, and string handling.

Uploaded by

COMPUTER SCIENCE
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)
6 views44 pages

Java Lab Program26

The document outlines several Java programs, including algorithms and code for printing prime numbers, multiplying matrices, counting characters, lines, and words in text, generating random numbers, and performing string manipulations. Each section provides a step-by-step algorithm followed by the corresponding Java code and sample outputs. The programs demonstrate various programming concepts such as loops, conditionals, and string handling.

Uploaded by

COMPUTER SCIENCE
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

1.

Print Prime Numbers up to a Given Integer


ALGORITHM
Step 1: Start the Program
Step 2: Import the Scanner class from [Link] package to take input from the user.
Step 3: Define the Class - Create a public class named PrimeNumbers.
Step 4: Create the Main Method
Step 5: Create Scanner Object to read user input.
Step 6: Take User Input and Store the value in variable limit.
Step 7: Display message showing prime numbers up to the given limit.
Step 8: Use Loop to Check Each Number starting from 2 up to limit.
Step 9: Call the function isPrime(i) to check if the number is prime.
Step 10: If the function returns true, print the number.
Step 11: Close the scanner to prevent memory leaks.
Steps Inside isPrime() Method
Step 12:Create a method isPrime(int n) that returns boolean.
Step 13: Check Base Condition
 If number is less than or equal to 1, return false.
Step 14: Check Divisibility of a number
Step 15: Displays all prime numbers up to the entered limit.
Step 16: Stop the Program
Program 1
import [Link];
public class PrimeNumbers
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
[Link]("Enter a positive integer: ");
int limit = [Link]();
[Link]("Prime numbers up to " + limit + ":");
for (int i = 2; i <= limit; i++)
{
if (isPrime(i)) {
[Link](i + " ");
}
}
[Link]();
}
public static boolean isPrime(int n)
{
if (n <= 1)
{
return false;
}
for (int i = 2; i <= [Link](n); i++)
{
if (n % i == 0) {
return false;
}
}
return true;
}
}
OUTPUT
Enter a positive integer: 30
Prime numbers up to 30:
2 3 5 7 11 13 17 19 23 29
2. Multiply Two Given Matrices

Algorithm

Step 1 : Start the Program


Step 2: Create a public class named Matrix Multiplication.
Step 3: Create the Main Method
Step 4: Define the number of rows and columns for Matrix A and Matrix B.
Step 5: Declare and initialize matrix A and matrix B with values.
Step 6: Check Multiplication Condition for the two matrix
Step 7: Create a new matrix C to store the result.
Step 8: Perform Matrix Multiplication
Step 9: Display Result Matrix
Step 10 : Stop the Program
Program
import [Link];
public class MatrixMultiplication {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter rows of first matrix: ");
int r1 = [Link]();
[Link]("Enter columns of first matrix: ");
int c1 = [Link]();
[Link]("Enter rows of second matrix: ");
int r2 = [Link]();
[Link]("Enter columns of second matrix: ");
int c2 = [Link]();
if (c1 != r2) {
[Link]("Matrices cannot be multiplied: columns of first matrix must equal
rows of second matrix.");
[Link]();
return;
}
int[][] A = new int[r1][c1];
int[][] B = new int[r2][c2];
[Link]("Enter elements of first matrix (" + r1 + "x" + c1 + "):");
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c1; j++) {
A[i][j] = [Link]();
}
}
[Link]("Enter elements of second matrix (" + r2 + "x" + c2 + "):");
for (int i = 0; i < r2; i++) {
for (int j = 0; j < c2; j++) {
B[i][j] = [Link]();
}
}
int[][] C = new int[r1][c2];
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
int sum = 0;
for (int k = 0; k < c1; k++) {
sum += A[i][k] * B[k][j];
}
C[i][j] = sum;
}
}
[Link]("Resultant matrix (" + r1 + "x" + c2 + "):");
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
[Link](C[i][j] + " ");
}
[Link]();
}
[Link]();
}
}
OUTPUT
Enter rows of first matrix: 3
Enter columns of first matrix: 3
Enter rows of second matrix: 3
Enter columns of second matrix: 3
Enter elements of first matrix (3x3):
1
1
1
1
1
1
1
1
1
Enter elements of second matrix (3x3):
2
2
2
2
2
2
2
2
2
Resultant matrix (3x3):
6 6 6
6 6 6
6 6 6
3. Display Number of Characters, Lines, and Words in a Text
Aim : A java Program to find the number of characters, lines and words in a
given text.

Procedure

Step 1: Start the program


Step 2: Import Scanner Class
Step 3: Define the Class
Step 4: Declares a public class named clw.
Step 5 :Define Main Method
Step 6: Create Scanner Object which allows input from the keyboard.
Step 7: Displays a message that Prompts User for Input
Step 8: Read the Input entered by the user and Stores it in a variable named str.
Step 9: Get Length of String and Stores the length of the string in variable len.
Step 10 : Convert String to Character Array
Step 11: Initialize Counters
int letter = 0;
int space = 0;
int num = 0;
int other = 0;
Step 12: Loop Through Each Character to Check each character one by one.
Step 13: Check Character Type and incrememnts its value.
Step 14: Display the Results
import [Link];
public class clw {
public static void main(String[] args)
{
Scanner in = new Scanner([Link]);
[Link]("Enter a sentence:");
String str = [Link]();
str += " ";
int len = [Link]();
char[] ch = [Link]();
int letter = 0;
int space = 0;
int num = 0;
int other = 0;
for (int i = 0; i < [Link](); i++) {
if ([Link](ch[i])) {
letter++;
}
else if ([Link](ch[i])) {
num++;
}
else if ([Link](ch[i])) {
space++;
}
else {
other++;
}
}
[Link]("letter: " + letter);
[Link]("space: " + space);
[Link]("number: " + num);
[Link]("other: " + other);
}}
OUTPUT
Enter a sentence: welcome to 3rd computer science
letter: 26
space: 4
number: 1
other: 0
4. Generate Random Numbers Between Two Limits and Print Messages
Aim:
A java Program to generate random numbers between any two numbers using
random class
Step 1: Start the program
Step 2: Import necessary Packages Random and Scanner
Step 3: Create a public class named RandomNumberRange.
Step 4: Create Main Method
Step 5: Create object of Scanner to read input and Create object of Random to generate
random numbers.
Step 6: get the Lower and Upper Limits from the user
Step 7: Check if lower limit is greater than or equal to upper limit.
Step 8: Generate Random Number Using the formula
[Link](upper−lower+1)+lower
 This generates a number between lower and upper (inclusive).
Step 9: Print the generated random number.
Step 10: Find Middle Value
 Calculate middle value of the range.
Step 11: Check Range Category
 If number < mid → Lower half
 If number == mid → Middle
 If number > mid → Upper half
Step 12: Print the result
Step 13:Close Scanner
Step 14: Stop the Program
Program 4:

import [Link];

import [Link];

public class RandomNumberRange {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

Random random = new Random();

[Link]("Enter lower limit: ");

int lower = [Link]();

[Link]("Enter upper limit: ");

int upper = [Link]();

if (lower >= upper) {

[Link]("Invalid range! Upper limit must be greater than lower limit.");

return;

int randomNumber = [Link](upper - lower + 1) + lower;

[Link]("Generated Random Number: " + randomNumber);

int mid = (lower + upper) / 2;

if (randomNumber < mid) {

[Link]("The number is in the LOWER half of the range.");

} else if (randomNumber == mid) {

[Link]("The number is exactly at the MIDDLE of the range.");

} else {

[Link]("The number is in the UPPER half of the range.");

[Link]();

}}
OUTPUT

Enter lower limit: 10

Enter upper limit: 15

Generated Random Number: 13

The number is in the UPPER half of the range.


5. String Manipulation using Character Array

Aim :

A java program to perform string operation using character array

Step 1: Start the program

Step 2: Import Required Classes

Step 3: Define the Class

Step 4: Define the Main Method

Step5: Take First String Input using scanner class object

Step6: Take Second String Input using scanner class object and Converts it into
character array.

Step7: Take Index Input and stores it in the variable..

Step8: Find Length of Both Strings

Step9: Get Character at Given Index

Step 10 :Concatenate Two Character Arrays and displays it.

Step 11: stop the Program


import [Link];

import [Link];

public class StringManipulation {

public static void main(String[] args) {

Scanner in = new Scanner([Link]);

[Link]("Enter a sentence:");

String st1 = [Link]();

char[] ch1 = [Link]();

Scanner at = new Scanner([Link]);

[Link]("Enter a sentence:");

String st2 = [Link]();

char[] ch2 = [Link]();

Scanner sc = new Scanner([Link]);

[Link]("Enter the index number");

int inn = [Link]();

int len1 = findLen(ch1);

int len2 = findLen(ch2);

[Link]("String 1 Length: " + len1);

[Link]("String 2 Length: " + len2);

char CAI = getCharAtIndex(ch1, inn);

[Link]("Character at index " + inn + " in String 1: " + CAI);

char[] concatStr = concatArr(ch1, ch2);

[Link]("Concatenated String: " + new String(concatStr));

public static int findLen(char[] arr)

return [Link];
}

public static char getCharAtIndex(char[] arr, int index)

if (index >= 0 && index < [Link])

return arr[index];

} else

throw new ArrayIndexOutOfBoundsException("Index is out of bounds");

public static char[] concatArr(char[] arr1, char[] arr2)

int combLeng = [Link] + [Link];

char[] result = new char[combLeng];

//[Link](sourceArray, sourceStart, destinationArray, destStart, length);

[Link](arr1, 0, result, 0, [Link]);

[Link](arr2, 0, result, [Link], [Link]);

return result;

}
OUTPUT
Enter a sentence:
THIRD COMPUTER
Enter a sentence:
SCIENCE
Enter the index number5
String 1 Length: 14
String 2 Length: 7
Character at index 5 in String 1:
Concatenated String: THIRD COMPUTERSCIENCE
6. String Operations using String Class

Aim : To perform basic String class operations in Java,

 String concatenation
 Searching for a substring
 Finding the index of a substring
 Extracting substrings from a given string.

Algorithm

Step 1: Start the program

Step 2: import Required Classes

Step 3: Define the main Class

Step 4: Read Main String from User and store it in mainSt.

1. Converts the string into a character array ch1 (not used later).

Step 5: Read Substring to Search string inside the main string and Store it in subst.

Step 6: Read Extra Word for Concatenation

Step 7: (a) String Concatenation

 Uses concat() method to join mainSt and xst.

(b) Search for a Substring

 Checks if subst exists inside mainSt.


 If found → prints found message.
 Else → prints not found.

[c] Find Position of Substring

 indexOf() returns:
o Starting index if found
o -1 if not found

(d) Extract Substring from main string from the given index value

Step 8 : Display the result

Step 9 : Stop the Program.


import [Link];
import [Link];
public class StringClassOps {
public static void main(String[] args) {
Scanner in = new Scanner([Link]);
[Link]("Enter a sentence:");
String mainSt = [Link]();
char[] ch1 = [Link]();
Scanner at = new Scanner([Link]);
[Link]("Enter a word to search :");
String subst = [Link]();
char[] ch2 = [Link]();
Scanner xt = new Scanner([Link]);
[Link]("Extra word to concatenate:");
String xst = [Link]();
char[] ch3 = [Link]();
// a. String Concatenation
String combined = [Link](xst);
[Link]("Concatenated string: " + combined);
// b. Search a substing
if ([Link](subst)) {
[Link]("Substring '" + subst + "' found in the main string.");
} else {
[Link]("Substring '" + subst + "' not found.");
}
// Can also use indexOf for position
[Link]("Index of '" + subst + "': " + [Link](subst));
// c. To extract substring from given string
// Extracts from index 5 to the end
String extracted1 = [Link](5);
[Link]("Substring from index 5: " + extracted1);

// Extracts from index 5 up to (but not including) index 17


String extracted2 = [Link](5, 17);
[Link]("Substring from index 5 to 17: " + extracted2);
}
}
OUTPUT
Enter a sentence:
SANGHAMAM COLLEGE
Enter a word to search:
MAM
Extra word to concatenate:
COMPUTER SCIENCE DEPT IS BEST
Concatenated string: SANGHAMAM COLLEGECOMPUTER SCIENCE DEPT IS BEST
Substring 'MAM' found in the main string.
Index of 'MAM': 6
Substring from index 5: AMAM COLLEGE
Substring from index 5 to 17: AMAM COLLEGE
7. String Operations using StringBuffer Class
import [Link];
public class StringBufferOperations {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
StringBuffer buffer;
[Link]("Enter an initial string for the StringBuffer:");
String initialString = [Link]();
buffer = new StringBuffer(initialString);
[Link]("Enter string to append:");
String strAppend = [Link]();
[Link](strAppend);
[Link]("Result: " + buffer);
[Link]("Enter string to insert:");
String strInsert = [Link]();
[Link]("Enter index to insert at:");
int indexInsert = [Link]();
[Link](); // Consume newline
try {
[Link](indexInsert, strInsert);
[Link]("Result: " + buffer);
} catch (IndexOutOfBoundsException e) {
[Link]("Error: Index out of bounds. Current length is " +
[Link]());
}

[Link]("Enter start index for deletion:");


int startIndex = [Link]();
[Link]("Enter end index (exclusive) for deletion:");
int endIndex = [Link]();
[Link](); // Consume newline
try {
[Link](startIndex, endIndex);
[Link]("Result: " + buffer);
} catch (IndexOutOfBoundsException e) {
[Link]("Error: Indices out of bounds. Current length is " +
[Link]());
}
[Link]();
[Link]("Result: " + buffer);
[Link]("Length: " + [Link]());
[Link]("Capacity: " + [Link]());
[Link]();
return;

}
}
OUTPUT

Enter an initial string for the StringBuffer:

COMPUTER

Enter string to append:

SCIENCE

Result: COMPUTERSCIENCE

Enter string to insert:

2ND

Enter index to insert at:

Result: 2NDCOMPUTERSCIENCE

Enter start index for deletion:

Enter end index (exclusive) for deletion:

Result: COMPUTERSCIENCE

Result: ECNEICSRETUPMOC

Length: 15

Capacity: 24
8. Multi-thread Application (Even/Odd Square/Cube)
import [Link];
public class randeoc {
public static void main(String args[])
{
Number n = new Number();
[Link]();
}
}
class Square extends Thread
{
int x;
Square(int n)
{
x = n;
}
public void run()
{
int sqr = x * x;
[Link]("Square of " + x + " = " + sqr );
}
}
class Cube extends Thread
{
int x;
Cube(int n)
{
x = n;
}
public void run()
{
int cub = x * x * x;
[Link]("Cube of " + x + " = " + cub );
}
}
class Number extends Thread
{
public void run()
{
Random random = new Random();
for(int i =0; i<10; i++)
{
int randomInteger = [Link](100);
[Link]("Random Integer generated : " + randomInteger);
Square s = new Square(randomInteger);
[Link]();
Cube c = new Cube(randomInteger);
[Link]();
try {
[Link](1000);
} catch (InterruptedException ex) {
[Link](ex);
}
}
}
}
OUTPUT

Random Integer generated : 45


Cube of 45 = 91125
Square of 45 = 2025
Random Integer generated : 31
Square of 31 = 961
Cube of 31 = 29791
Random Integer generated : 11
Square of 11 = 121
Cube of 11 = 1331
Random Integer generated : 87
Square of 87 = 7569
Cube of 87 = 658503
Random Integer generated : 65
Square of 65 = 4225
Cube of 65 = 274625
Random Integer generated : 23
Square of 23 = 529
Cube of 23 = 12167
Random Integer generated : 62
Square of 62 = 3844
Cube of 62 = 238328
Random Integer generated : 20
Square of 20 = 400
Cube of 20 = 8000
Random Integer generated : 1
Square of 1 = 1
Cube of 1 = 1
Random Integer generated : 8
Square of 8 = 64
Cube of 8 = 512
9. Threading Program with Asynchronous Method Calls

OUTPUT

Thread-1: 90
Thread-0: 1
Thread-1: 91
Thread-0: 2
Thread-1: 92
Thread-0: 3
Thread-1: 93
Thread-0: 4
Thread-1: 94
Thread-0: 5
Thread-1: 95
Thread-0: 6
Thread-1: 96
Thread-0: 7
Thread-1: 97
Thread-0: 8
Thread-1: 98
Thread-0: 9
Thread-1: 99
Thread-0: 10
Thread-1: 100
10. Demonstrate Use of Exceptions

import [Link];

public class ExceptionDemo {


public static void main(String[] args) {
try {
int result = 5 / 0;
[Link]("Result of division: " + result);
} catch (ArithmeticException e) {
[Link]("Arithmetic Exception caught: Division by zero");
}
try {
String str = "abc";
int num = [Link](str);
[Link]("Parsed number: " + num);
} catch (NumberFormatException e) {
[Link]("Number Format Exception caught: Invalid number format");
}
try {
int[] arr = {1, 2, 3};
[Link]("Accessing element at index 3: " + arr[3]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("ArrayIndexOutOfBoundsException caught: Index out of bounds");
}
try {
int[] negativeArray = new int[-3];
[Link]("Array created successfully with size: " + [Link]);
} catch (NegativeArraySizeException e) {
[Link]("NegativeArraySizeException caught: Negative array size");
}
}
}
OUTPUT

Arithmetic Exception caught: Division by zero


Number Format Exception caught: Invalid number format
ArrayIndexOutOfBoundsException caught: Index out of bounds
NegativeArraySizeException caught: Negative array size
11. File Information Program
import [Link];
import [Link];
public class FileInfo {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Prompt user for the file name
[Link]("Enter the file name (with path if necessary): ");
String fileName = [Link]();
// Create a File object
File file = new File(fileName);
// Check if the file exists
if ([Link]()) {
[Link]("File exists: Yes");
// Check if the file is readable
[Link]("Readable: " + ([Link]() ? "Yes" : "No"));
// Check if the file is writable
[Link]("Writable: " + ([Link]() ? "Yes" : "No"));
// Get the file type (directory or file)
if ([Link]()) {
[Link]("Type: Directory");
} else {
[Link]("Type: File");
}
// Get the length of the file in bytes
[Link]("Length: " + [Link]() + " bytes");
} else {
[Link]("File exists: No");
}
// Close the scanner
[Link]();
}
}
12. Text Modifier with Frames and Controls
import [Link].*;
import [Link].*;

public class TextModifier extends Frame implements ActionListener, ItemListener {


private TextField textInput;
private Choice fontChoice, sizeChoice;
private Checkbox boldCheckbox, italicCheckbox;
private Button applyButton;
private Label displayLabel;
private Font currentFont;

public TextModifier() {
setTitle("Text Modifier");
setLayout(new FlowLayout());
setSize(500, 300);

textInput = new TextField("Sample Text", 20);


fontChoice = new Choice();
[Link]("Serif");
[Link]("SansSerif");
[Link]("Monospaced");
[Link](this);

sizeChoice = new Choice();


for (int i = 12; i <= 48; i += 4) {
[Link]([Link](i));
}
[Link](this);

boldCheckbox = new Checkbox("Bold");


italicCheckbox = new Checkbox("Italic");
[Link](this);
[Link](this);
applyButton = new Button("Apply Changes");
[Link](this);

displayLabel = new Label("Sample Text", [Link]);


currentFont = new Font("Serif", [Link], 12);
[Link](currentFont);

add(new Label("Enter Text:"));


add(textInput);
add(new Label("Font:"));
add(fontChoice);
add(new Label("Size:"));
add(sizeChoice);
add(boldCheckbox);
add(italicCheckbox);
add(applyButton);
add(displayLabel);

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

public void actionPerformed(ActionEvent e) {


[Link]([Link]());
updateFont();
}

public void itemStateChanged(ItemEvent e) {


updateFont();
}

private void updateFont() {


String fontName = [Link]();
int fontSize = [Link]([Link]());
int fontStyle = [Link];
if ([Link]()) {
fontStyle |= [Link];
}
if ([Link]()) {
fontStyle |= [Link];
}
currentFont = new Font(fontName, fontStyle, fontSize);
[Link](currentFont);
}

public static void main(String[] args) {


new TextModifier();
}
}
13. Mouse Event Handler (Adapter Classes)

Step 1: Start the program

Step 2: Import Required Packages

Step 3: Create a Class Extending JFrame

Step 4: Declare Components to display text messages.

Step 5: Create Constructor To initializes the window and components.

Step 6: Set Frame Properties like window title, window size (width, height).

Step 7: Creates label with default message, Sets font style and size and Add label to center
of the frame.

Step 8: Add Mouse Listener to handle mouse events.

Step 9: Make Frame Visible to display the window using setVisible(true);

Step 10: Create Main Method and call the method MouseEventDemo.

Step 11: Display the result.

Step 12: Stop the Program.


import [Link].*;
import [Link].*;

public class MouseEventDemo extends Frame {


private String statusMessage = "No mouse event yet.";
private int mouseX = 100, mouseY = 100;

public MouseEventDemo() {
addMouseListener(new MyMouseAdapter());
addMouseMotionListener(new MyMouseMotionAdapter());
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
[Link](0);
}
});
setSize(400, 400);
setTitle("Mouse Events");
setVisible(true);
}

// Inner class to handle MouseListener events


class MyMouseAdapter extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
statusMessage = "Mouse Clicked";
mouseX = [Link]();
mouseY = [Link]();
repaint();
}
public void mousePressed(MouseEvent e) {
statusMessage = "Mouse Pressed";
mouseX = [Link]();
mouseY = [Link]();
repaint();
}
public void mouseReleased(MouseEvent e) {
statusMessage = "Mouse Released";
mouseX = [Link]();
mouseY = [Link]();
repaint();
}
public void mouseEntered(MouseEvent e) {
statusMessage = "Mouse Entered Window";
repaint();
}
public void mouseExited(MouseEvent e) {
statusMessage = "Mouse Exited Window";
repaint();
}
}

// Inner class to handle MouseMotionListener events


class MyMouseMotionAdapter extends MouseMotionAdapter {
public void mouseDragged(MouseEvent e) {
statusMessage = "Mouse Dragged at (" + [Link]() + ", " + [Link]() + ")";
mouseX = [Link]();
mouseY = [Link]();
repaint();
}
public void mouseMoved(MouseEvent e) {
statusMessage = "Mouse Moved at (" + [Link]() + ", " + [Link]() + ")";
mouseX = [Link]();
mouseY = [Link]();
repaint();
}
}

public void paint(Graphics g) {


// Clear previous message by repainting the background
[Link]([Link]);
[Link](0, 0, getWidth(), getHeight());

[Link]([Link]);
// Center the message
FontMetrics fm = [Link]();
int x = (getWidth() - [Link](statusMessage)) / 2;
int y = (getHeight() - [Link]()) / 2 + [Link]();
[Link](statusMessage, x, y);
}

public static void main(String[] args) {


new MouseEventDemo();
}
}
14. Simple Calculator with Grid Layout
import [Link].*;
import [Link].*;

public class SimpleCalculator extends Frame implements ActionListener {


private TextField display;
private Button[] buttons;
private String[] buttonLabels = {
"7", "8", "9", "+",
"4", "5", "6", "-",
"1", "2", "3", "*",
"C", "0", "=", "/"
};
private double firstOperand = 0;
private String operator = "";
private boolean startOfNumber = true;

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

display = new TextField("0", 20);


[Link](false);
[Link](new Font("Arial", [Link], 20));
add(display, [Link]);

Panel buttonPanel = new Panel();


[Link](new GridLayout(4, 4, 5, 5));
buttons = new Button[16];

for (int i = 0; i < 16; i++) {


buttons[i] = new Button(buttonLabels[i]);
buttons[i].addActionListener(this);
[Link](buttons[i]);
}
add(buttonPanel, [Link]);

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

public void actionPerformed(ActionEvent e) {


String command = [Link]();

if ([Link]([Link](0)) || [Link](".")) {
if (startOfNumber) {
[Link](command);
startOfNumber = false;
} else {
[Link]([Link]() + command);
}
} else if ([Link]("C")) {
[Link]("0");
startOfNumber = true;
firstOperand = 0;
operator = "";
} else if ([Link]("=")) {
if (![Link]()) {
try {
double secondOperand = [Link]([Link]());
double result = calculate(firstOperand, secondOperand, operator);
[Link]([Link](result));
firstOperand = result;
operator = "";
startOfNumber = true;
} catch (ArithmeticException ex) {
[Link]("Error: " + [Link]());
firstOperand = 0;
startOfNumber = true;
}
}
} else { // Operator buttons (+, -, *, /)
if (!startOfNumber) {
firstOperand = [Link]([Link]());
operator = command;
startOfNumber = true;
}
}
}

private double calculate(double op1, double op2, String op) throws ArithmeticException {
switch (op) {
case "+": return op1 + op2;
case "-": return op1 - op2;
case "*": return op1 * op2;
case "/":
if (op2 == 0) {
throw new ArithmeticException("Divide by zero");
}
return op1 / op2;
default: return 0;
}
}

public static void main(String[] args) {


new SimpleCalculator();
}
}
15. Traffic Light Simulator with Radio Buttons
import [Link].*;
import [Link].*;
public class TrafficLightSimulator extends Frame implements ItemListener {
private Checkbox red, yellow, green;
private CheckboxGroup colorGroup;
private Label messageLabel;
private String statusMessage = "";
public TrafficLightSimulator() {
setTitle("Traffic Light Simulator");
setLayout(new FlowLayout());
setSize(300, 200);
colorGroup = new CheckboxGroup();
red = new Checkbox("Red", colorGroup, false);
yellow = new Checkbox("Yellow", colorGroup, false);
green = new Checkbox("Green", colorGroup, false);
[Link](this);
[Link](this);
[Link](this);
messageLabel = new Label("Select a light", [Link]);
[Link](new Font("Serif", [Link], 16));
add(red);
add(yellow);
add(green);
add(messageLabel);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
[Link](0);
}
});
setVisible(true);
}
public void itemStateChanged(ItemEvent e) {
if ([Link]() == red) {
statusMessage = "STOP";
[Link]([Link]);
} else if ([Link]() == yellow) {
statusMessage = "READY";
[Link]([Link]);
} else if ([Link]() == green) {
statusMessage = "GO";
[Link]([Link]);
}
[Link](statusMessage);
}
public static void main(String[] args) {
new TrafficLightSimulator();
}
}

You might also like