0% found this document useful (0 votes)
14 views14 pages

Untitled Document

document

Uploaded by

jnananya2006
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)
14 views14 pages

Untitled Document

document

Uploaded by

jnananya2006
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
You are on page 1/ 14

Java programs

Simple calculator:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Calculator extends JFrame {


private JTextField display;
private double result = 0;
private String lastCommand = "=";
private boolean start = true;

public Calculator() {
// Set up the frame
setTitle("Simple Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 400);
setLayout(new BorderLayout());

// Create display field


display = new JTextField("0");
display.setEditable(false);
display.setHorizontalAlignment(JTextField.RIGHT);
display.setFont(new Font("Arial", Font.PLAIN, 20));
add(display, BorderLayout.NORTH);

// Create button panel


JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(5, 4, 5, 5));

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

for (String label : buttonLabels) {


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

add(buttonPanel, BorderLayout.CENTER);
}

private class ButtonClickListener implements ActionListener {


public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();

if (command.matches("[0-9.]")) {
if (start) {
display.setText(command);
start = false;
} else {
display.setText(display.getText() + command);
}
} else if (command.matches("[+\\-*/%]")) {
try {
double x = Double.parseDouble(display.getText());
calculate(x);
lastCommand = command;
start = true;
} catch (NumberFormatException ex) {
display.setText("Error");
}
} else if (command.equals("=")) {
try {
double x = Double.parseDouble(display.getText());
calculate(x);
lastCommand = "=";
start = true;
} catch (NumberFormatException ex) {
display.setText("Error");
}
} else if (command.equals("C")) {
result = 0;
lastCommand = "=";
start = true;
display.setText("0");
}
}
private void calculate(double x) {
try {
if (lastCommand.equals("+")) result += x;
else if (lastCommand.equals("-")) result -= x;
else if (lastCommand.equals("*")) result *= x;
else if (lastCommand.equals("/")) {
if (x == 0) throw new ArithmeticException("Division by zero");
result /= x;
}
else if (lastCommand.equals("%")) {
if (x == 0) throw new ArithmeticException("Division by zero");
result %= x;
}
else if (lastCommand.equals("=")) result = x;

display.setText(String.valueOf(result));
} catch (ArithmeticException ex) {
display.setText("Cannot divide by zero");
result = 0;
start = true;
}
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
Calculator calc = new Calculator();
calc.setVisible(true);
});
}
}

2.Write a Java program that creates a user interface to perform integer divisions. The
user enters two numbers in the text fields, Num1 and Num2. The division of Num1 and
Num 2 is displayed in the Result field when the Divide button is clicked. If Num1 or Num2
were not an integer, the program would throw a Number Format Exception. If Num2 were
Zero, the program would throw an Arithmetic Exception. Display the exception in a
message dialog box.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class IntegerDivisionCalculator extends JFrame {


private JTextField num1Field, num2Field, resultField;
private JButton divideButton;

public IntegerDivisionCalculator() {
setTitle("Integer Division Calculator");
setLayout(new GridLayout(4, 2, 10, 10));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Initialize components
JLabel num1Label = new JLabel("Num1:");
JLabel num2Label = new JLabel("Num2:");
JLabel resultLabel = new JLabel("Result:");

num1Field = new JTextField(10);


num2Field = new JTextField(10);
resultField = new JTextField(10);
resultField.setEditable(false);

divideButton = new JButton("Divide");

// Add components to frame


add(num1Label);
add(num1Field);
add(num2Label);
add(num2Field);
add(resultLabel);
add(resultField);
add(new JLabel()); // Empty label for spacing
add(divideButton);

// Add action listener to button


divideButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
performDivision();
}
});

// Set frame properties


setSize(300, 200);
setLocationRelativeTo(null);
setVisible(true);
}

private void performDivision() {


try {
// Parse input values
int num1 = Integer.parseInt(num1Field.getText());
int num2 = Integer.parseInt(num2Field.getText());

// Check for division by zero


if (num2 == 0) {
throw new ArithmeticException("Division by zero is not allowed");
}

// Perform division and display result


int result = num1 / num2;
resultField.setText(String.valueOf(result));

} catch (NumberFormatException ex) {


JOptionPane.showMessageDialog(this,
"Please enter valid integers in both fields",
"Number Format Error",
JOptionPane.ERROR_MESSAGE);
resultField.setText("");

} catch (ArithmeticException ex) {


JOptionPane.showMessageDialog(this,
ex.getMessage(),
"Arithmetic Error",
JOptionPane.ERROR_MESSAGE);
resultField.setText("");
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
new IntegerDivisionCalculator();
});
}
}
3.Write a Java program that implements a multi-thread application that has three threads.
First thread generates a 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 the cube of the number.
import javax.swing.*;
import java.awt.*;
import java.util.Random;

public class MultiThreadApplication extends JFrame {


private JTextArea outputArea;
private volatile boolean isRunning = true;
private Random random = new Random();

public MultiThreadApplication() {
setTitle("Multi-Thread Application");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

// Initialize components
outputArea = new JTextArea(20, 40);
outputArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(outputArea);
add(scrollPane, BorderLayout.CENTER);

// Create and start threads


Thread generatorThread = new Thread(new NumberGenerator());
Thread evenThread = new Thread(new EvenNumberHandler());
Thread oddThread = new Thread(new OddNumberHandler());

generatorThread.start();
evenThread.start();
oddThread.start();

// Set frame properties


setSize(500, 400);
setLocationRelativeTo(null);
setVisible(true);
}

private void appendText(String text) {


SwingUtilities.invokeLater(() -> {
outputArea.append(text + "\n");
});
}

// Thread 1: Generates random numbers


private class NumberGenerator implements Runnable {
@Override
public void run() {
while (isRunning) {
try {
int number = random.nextInt(100); // Generate random number between 0-99
appendText("Generated: " + number);
synchronized (MultiThreadApplication.this) {
MultiThreadApplication.this.notifyAll(); // Notify other threads
}

Thread.sleep(1000); // Wait for 1 second


} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
}
}

// Thread 2: Handles even numbers


private class EvenNumberHandler implements Runnable {
@Override
public void run() {
while (isRunning) {
synchronized (MultiThreadApplication.this) {
try {
MultiThreadApplication.this.wait();
int number = Integer.parseInt(
outputArea.getText().split("\n")[outputArea.getLineCount()-1]
.split(": ")[1]
);

if (number % 2 == 0) {
appendText("Even number detected: " + number);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
}
}
}

// Thread 3: Handles odd numbers


private class OddNumberHandler implements Runnable {
@Override
public void run() {
while (isRunning) {
synchronized (MultiThreadApplication.this) {
try {
MultiThreadApplication.this.wait();
int number = Integer.parseInt(
outputArea.getText().split("\n")[outputArea.getLineCount()-1]
.split(": ")[1]
);

if (number % 2 != 0) {
appendText("Odd number detected: " + number);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}

}
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
new MultiThreadApplication();
});
}
}
4.doubly linked list
import java.util.Scanner;

class Node {
int data;
Node prev;
Node next;

Node(int data) {
this.data = data;
this.prev = null;
this.next = null;
}
}

class DoublyLinkedList {
Node head;
Node tail;

DoublyLinkedList() {
head = null;
tail = null;
}

// Insert at front
void insertFront(int data) {
Node newNode = new Node(data);

if (head == null) {
head = tail = newNode;
} else {
newNode.next = head;
head.prev = newNode;
head = newNode;
}
System.out.println("Inserted " + data + " at front");
}

// Insert at back
void insertBack(int data) {
Node newNode = new Node(data);

if (tail == null) {
head = tail = newNode;
} else {
newNode.prev = tail;
tail.next = newNode;
tail = newNode;
}
System.out.println("Inserted " + data + " at back");
}

// Delete a given element


void delete(int key) {
Node current = head;

// If list is empty
if (head == null) {
System.out.println("List is empty");
return;
}

// Search for the key


while (current != null && current.data != key) {
current = current.next;
}

// If key not found


if (current == null) {
System.out.println("Element " + key + " not found");
return;
}

// If node to be deleted is head


if (current == head) {
head = head.next;
if (head != null) {
head.prev = null;
} else {
tail = null; // List becomes empty
}
}
// If node to be deleted is tail
else if (current == tail) {
tail = tail.prev;
tail.next = null;
}
// If node to be deleted is in middle
else {
current.prev.next = current.next;
current.next.prev = current.prev;
}
System.out.println("Deleted " + key);
}

// Display the list


void display() {
if (head == null) {
System.out.println("List is empty");
return;
}

System.out.println("List contents:");
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
}

public class Main {


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

while (true) {
System.out.println("\nDoubly Linked List Operations:");
System.out.println("1. Insert at Front");
System.out.println("2. Insert at Back");
System.out.println("3. Delete Element");
System.out.println("4. Display List");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");

int choice = scanner.nextInt();

switch (choice) {
case 1:
System.out.print("Enter element to insert at front: ");
int frontElement = scanner.nextInt();
list.insertFront(frontElement);
break;

case 2:
System.out.print("Enter element to insert at back: ");
int backElement = scanner.nextInt();
list.insertBack(backElement);
break;

case 3:
System.out.print("Enter element to delete: ");
int deleteElement = scanner.nextInt();
list.delete(deleteElement);
break;

case 4:
list.display();
break;

case 5:
System.out.println("Exiting program...");
scanner.close();
System.exit(0);
break;

default:
System.out.println("Invalid choice! Please try again.");
}
}
}
}
5.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
the selected color. Initially, there is no message shown.
import javax.swing.*;
import java.awt.*;

public class TrafficLightSimulation extends JFrame {


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

public TrafficLightSimulation() {
setTitle("Traffic Light Simulation");
setLayout(new BorderLayout(10, 10));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create panels
JPanel messagePanel = new JPanel();
JPanel buttonPanel = new JPanel();

// Initialize components
messageLabel = new JLabel(" ");
messageLabel.setFont(new Font("Arial", Font.BOLD, 24));

redButton = new JRadioButton("Red");


yellowButton = new JRadioButton("Yellow");
greenButton = new JRadioButton("Green");
// Group the radio buttons
buttonGroup = new ButtonGroup();
buttonGroup.add(redButton);
buttonGroup.add(yellowButton);
buttonGroup.add(greenButton);

// Add components to panels


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

// Add panels to frame


add(messagePanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);

// Add action listeners


redButton.addActionListener(e -> updateLight("red"));
yellowButton.addActionListener(e -> updateLight("yellow"));
greenButton.addActionListener(e -> updateLight("green"));

// Set frame properties


setSize(300, 200);
setLocationRelativeTo(null);
setVisible(true);
}

private void updateLight(String color) {


switch (color.toLowerCase()) {
case "red":
messageLabel.setText("STOP");
messageLabel.setForeground(Color.RED);
break;

case "yellow":
messageLabel.setText("READY");
messageLabel.setForeground(Color.YELLOW);
break;

case "green":
messageLabel.setText("GO");
messageLabel.setForeground(Color.GREEN);
break;
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
new TrafficLightSimulation();
});
}
}

You might also like