[go: up one dir, main page]

0% found this document useful (0 votes)
28 views24 pages

Record Lab

Reference
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)
28 views24 pages

Record Lab

Reference
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/ 24

PROGRAM

import java.io.*;
import java.util.Scanner;

public class FileExceptionHandling{

public static void main(String[] args) {


// Specify the input and output file paths
String inputFile = "input.txt";
String outputFile = "output.txt";

Scanner scanner = null;


FileWriter writer = null;

try {
// Read from file
scanner = new Scanner(new File(inputFile));
String content = "";
while (scanner.hasNextLine()) {
content += scanner.nextLine() + "\n";
}

// Write to file
writer = new FileWriter(outputFile);
writer.write(content);

System.out.println("File read and write successful.");

} catch (FileNotFoundException e) {
System.err.println("Error: Input file not found - " + e.getMessage());
} catch (IOException e) {
System.err.println("Error: IO exception - " + e.getMessage());
} finally {
// Close resources in the finally block
if (scanner != null) {
scanner.close();
}
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
System.err.println("Error closing FileWriter - " + e.getMessage());
}
}
}}}
OUTPUT
PROGRAM
import java.lang.Thread;
import java.util.Random;
import java.lang.Math;

class RandomGen extends Thread{


public void run(){
Random rand = new Random();

while(true){
int num = rand.nextInt(300);
if(num%2 == 0){
Even even = new Even(num);
even.start();
}else{
Odd odd = new Odd(num);
odd.start();
}
try{
this.sleep(1000);
}catch(Exception e){
System.out.println("An error occurred");
}

}
}
}

class Odd extends Thread{


private int num;

Odd(int num){
this.num = num;
}

public void run(){


System.out.println(Math.pow(this.num, 3));
}
}

class Even extends Thread{


private int num;

Even(int num){
this.num = num;
}
public void run(){
System.out.println(Math.pow(this.num, 2));
}
}

public class MultiiThreading {


public static void main(String[] args) {
RandomGen rand = new RandomGen();
rand.start();
}
}
OUTPUT
PROGRAM
class Counter {
private int count = 0;

// Synchronized method to increment the count


public synchronized void increment() {
count++;
}

// Synchronized method to get the current count


public synchronized int getCount() {
return count;
}
}

class IncrementThread extends Thread {


private final Counter counter;

public IncrementThread(Counter counter) {


this.counter = counter;
}

@Override
public void run() {
for (int i = 0; i < 3; i++) {
counter.increment();
System.out.println("Count " + counter.getCount());
}
}
}

public class ThreadSynchronisationExample {

public static void main(String[] args) throws InterruptedException {


// Create a shared Counter object
Counter counter = new Counter();

// Create two threads that increment the counter


Thread thread1 = new IncrementThread(counter);
Thread thread2 = new IncrementThread(counter);

// Start the threads


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

// Wait for both threads to finish


thread1.join();
thread2.join();

// Print the final count


System.out.println("Final Count: " + counter.getCount());
}
}
OUTPUT
PROGRAM
import java.util.StringTokenizer;
import java.util.Scanner;

public class TokenizerDemo {


public static int[] tokenize(String input) {
StringTokenizer tokenizer = new StringTokenizer(input);

int[] nums = new int[tokenizer.countTokens()];


for(int i=0; i<nums.length; i++) {
nums[i] = Integer.parseInt(tokenizer.nextToken());
}

return nums;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.println("Enter a series of numbers: ");


int[] nums = tokenize(scanner.nextLine());

int sum = 0;
for(int i=0; i<nums.length; i++) {
System.out.println(nums[i]);
sum += nums[i];
}

System.out.println("The sum is " + sum);

}
OUTPUT
PROGRAM
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.StringTokenizer;

public class Calculator extends JFrame implements ActionListener{


private JLabel inputLabel;
Calculator(){
this.setTitle("Calculator");
this.setSize(600, 800);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setBackground(Color.WHITE);

//setting up root panel


JPanel rootPanel = new JPanel();
rootPanel.setLayout(new BoxLayout(rootPanel, BoxLayout.Y_AXIS));

//setting up text label


this.inputLabel = new JLabel("0", SwingConstants.RIGHT);
this.inputLabel.setFont(new Font("Arial", Font.BOLD, 96));
rootPanel.add(inputLabel);

//setting up buttons
JPanel buttonsPanel = new JPanel();
buttonsPanel.setLayout(new GridLayout(5, 4));

//setting up button colors


Color gray = new Color(231, 231, 231);
Color blue = new Color(73, 159, 239);
String[] numPadStrings = {"DEL", "AC", "x", "/", "7", "8", "9", "+", "4", "5", "6", "-",
"1", "2", "3", "=", "0", "."};
for(String button: numPadStrings){
JButton num = new JButton(String.valueOf(button));
num.setFont(new Font("Arial", Font.BOLD, 36));
num.setBorder(BorderFactory.createEmptyBorder());
num.setActionCommand(button);
if(button.equals("=")){
num.setBackground(blue);
}else{
num.setBackground(gray);
}

num.addActionListener(this);
buttonsPanel.add(num);
}

rootPanel.add(buttonsPanel);
this.add(rootPanel);

public void actionPerformed(ActionEvent e){


switch (e.getActionCommand()){
case "DEL" :
this.inputLabel.setText(this.inputLabel.getText().substring(0,
this.inputLabel.getText().length()-1));
break;
case "AC":
this.inputLabel.setText("0");
break;
case "=":
if(this.inputLabel.getText().contains("+")){
StringTokenizer tokenizer = new StringTokenizer(this.inputLabel.getText(),
"+");
this.inputLabel.setText(String.valueOf(Double.parseDouble(tokenizer.nextTok
en()) + Double.parseDouble((tokenizer.nextToken()))));
}else if(this.inputLabel.getText().contains("-")){
StringTokenizer tokenizer = new StringTokenizer(this.inputLabel.getText(),
"-");
this.inputLabel.setText(String.valueOf(Double.parseDouble(tokenizer.nextTok
en()) - Double.parseDouble((tokenizer.nextToken()))));
}else if(this.inputLabel.getText().contains("x")){
StringTokenizer tokenizer = new StringTokenizer(this.inputLabel.getText(),
"x");
this.inputLabel.setText(String.valueOf(Double.parseDouble(tokenizer.nextTok
en()) * Double.parseDouble((tokenizer.nextToken()))));
}else if(this.inputLabel.getText().contains("/")){
StringTokenizer tokenizer = new StringTokenizer(this.inputLabel.getText(),
"/");
this.inputLabel.setText(String.valueOf(Double.parseDouble(tokenizer.nextTok
en()) / Double.parseDouble((tokenizer.nextToken()))));
}
break;
default:
if(this.inputLabel.getText().equals("0")){
this.inputLabel.setText(e.getActionCommand());
}else{
this.inputLabel.setText(this.inputLabel.getText() + e.getActionCommand());
}
}

public static void main(String[] args) {


Calculator calc = new Calculator();
calc.setVisible(true);
}
}
OUTPUT
PROGRAM
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TrafficLight extends JFrame implements ActionListener {


private JRadioButton redButton, yellowButton, greenButton;
private TrafficLightPanel lightPanel;

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

redButton = new JRadioButton("Red");


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

ButtonGroup buttonGroup = new ButtonGroup();


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

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

JPanel controlPanel = new JPanel();


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

lightPanel = new TrafficLightPanel();

add(controlPanel, BorderLayout.NORTH);
add(lightPanel, BorderLayout.CENTER);

setVisible(true);
}

public void actionPerformed(ActionEvent e) {


if (e.getSource() == redButton) {
lightPanel.setColors(Color.RED, Color.LIGHT_GRAY, Color.LIGHT_GRAY);
} else if (e.getSource() == yellowButton) {
lightPanel.setColors(Color.LIGHT_GRAY, Color.YELLOW,
Color.LIGHT_GRAY);
} else if (e.getSource() == greenButton) {
lightPanel.setColors(Color.LIGHT_GRAY, Color.LIGHT_GRAY, Color.GREEN);
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(TrafficLight::new);
}
}

class TrafficLightPanel extends JPanel {


private Color color1, color2, color3;

public TrafficLightPanel() {
setPreferredSize(new Dimension(100, 300));
setColors(Color.LIGHT_GRAY, Color.LIGHT_GRAY, Color.LIGHT_GRAY);
}

public void setColors(Color c1, Color c2, Color c3) {


color1 = c1;
color2 = c2;
color3 = c3;
repaint();
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

int diameter = 80;


int x = getWidth() / 2 - diameter / 2;
int y = getHeight() / 6;

g.setColor(color1);
g.fillOval(x, y, diameter, diameter);

g.setColor(color2);
g.fillOval(x, y + diameter + 10, diameter, diameter);

g.setColor(color3);
g.fillOval(x, y + 2 * (diameter + 10), diameter, diameter);
}
}
OUTPUT
PROGRAM
import java.util.*;
class QuickSort {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.print("\nEnter the number of strings: ");
int n = scan.nextInt();
String array[] = new String[n];
for (int i = 0; i < n; i++) {
System.out.print("Enter the string " + (i + 1) + ": ");
array[i] = scan.next();
}
scan.close();
QuickSort quicksort = new QuickSort();
quicksort.qSort(array, 0, (n - 1));
System.out.println("\nSORTED ARRAY");
printArray(array);
}
public int partition(String array[], int low, int high) {
String pivot = array[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (array[j].compareTo(pivot) < 0) {
i++;
String temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
String temp = array[i + 1];
array[i + 1] = array[high];
array[high] = temp;
return i + 1;
}
public void qSort(String array[], int low, int high) {
if (low < high) {
int pi = partition(array, low, high);
qSort(array, low, pi - 1);
qSort(array, pi + 1, high);
}
}
static void printArray(String array[]) {
for (int i = 0; i < array.length; i++)
System.out.print(array[i] + " ");
}
}
OUTPUT
PROGRAM
import java.util.*;
class DList {
static LinkedList<Integer> list = new LinkedList<Integer>();
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int element;
while (true) {
System.out.print("\nSelect an operation: \n");
System.out.print(
"\n1.Add element to List" +
"\n2.Delete from front" +
"\n3.Delete from end" +
"\n4.Delete from a position" +
"\n5.Display List" +
"\n6.Exit" +
"\n\nEnter an operation number: "
);
int choice = scan.nextInt();
switch (choice) {
case 1:
// Add element to list
System.out.print("\nEnter element to add: ");
element = scan.nextInt();
list.add(element);
System.out.println("[" + element + " added to list]");
display();
break;
case 2:
// Delete from front
try {
element = list.getFirst();
list.removeFirst();
System.out.println("[" + element + " deleted from list]");
display();
} catch (NoSuchElementException e) {
System.out.println("[List is empty]");
}
break;
case 3:
// Delete from end
try {
element = list.getLast();
list.removeLast();
System.out.println("[" + element + " deleted from list]");
display();
} catch (NoSuchElementException e) {
System.out.println("[List is empty]");
}
break;
case 4:
// Delete from a position
System.out.print("\nEnter position: ");
int position = scan.nextInt();
try {
element = list.get(position - 1);
list.remove(position - 1);
System.out.println("[" + element + " deleted from list]");
display();
} catch (IndexOutOfBoundsException e) {System.out.println("[Invalid
position]");
}
break;
case 5:
// Display list
display();
break;
case 6:
// Exit
scan.close();
System.exit(0);
break;
default:
System.out.println("[Invalid choice. Please try again]");
}
}
}
static void display() {
System.out.print("\nList: ");
Iterator<Integer> itr = list.iterator();
while (itr.hasNext()) {
System.out.print(itr.next() + " ");
}
// for (int items : list)
// System.out.print(items + " ");
// System.out.println();
}
}
OUTPUT

You might also like