0% found this document useful (0 votes)
7 views53 pages

OOP Record Model

The document is a laboratory record notebook from Rajalakshmi Institute of Technology, containing various programming exercises and their implementations in Java. Each exercise includes aims, algorithms, programs, outputs, and results, covering topics such as summation, prime checking, Fibonacci sequences, class attributes, shape inheritance, banking systems, exception handling, multi-threading, and tree traversal algorithms. It serves as a practical examination record for students in the specified academic year.

Uploaded by

ashwineshwer01
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)
7 views53 pages

OOP Record Model

The document is a laboratory record notebook from Rajalakshmi Institute of Technology, containing various programming exercises and their implementations in Java. Each exercise includes aims, algorithms, programs, outputs, and results, covering topics such as summation, prime checking, Fibonacci sequences, class attributes, shape inheritance, banking systems, exception handling, multi-threading, and tree traversal algorithms. It serves as a practical examination record for students in the specified academic year.

Uploaded by

ashwineshwer01
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/ 53

RAJALAKSHMI INSTITUTE OF TECHNOLOGY

KUTHAMBAKKAM, CHENNAI - 600 124

Laboratory Record Note Book

NAME ...............................................................................................

REGISTER No. .................................................................................................

SUB CODE/NAME .........................................................................................

DEPARTMENT .................................................................................................

SEM/YEAR ..................................................................................................

ACADEMIC YEAR ........................................................................................


RAJALAKSHMI INSTITUTE OF TECHNOLOGY
KUTHAMBAKKAM, CHENNAI - 600 124

BONAFIDE CERTIFICATE

Signature Signature
Faculty - in - H.O.D
Charge

Submitted for the Practical Examination held


on............................................
Internal Examiner External
Examiner
INDEX
Name: Branch: Sec : Roll No. :
S.No. Date Title Page No.
INDEX
Name: Branch: Sec : Roll No. :
S.No. Date Title Page No.
EX NO: 01
DATE: FIND THE SUM OF ALL NUMBERS FROM 1 TO 100

Aim:

Algorithm:
REG. NO: 2117230070019

Program:

public class SumCalculator {


public static void main(String[] args) {
int sumResult = 0;
for (int i = 1; i <= 100; i++) {
sumResult += i;
}
System.out.println("The sum of all numbers from 1 to 100 is: " + sumResult);
}
}

Output:

The sum of all numbers from 1 to 100 is: 5050

Result:

1
EX NO: 02
DATE: CHECKING FOR PRIME NUMBER

Aim:

Algorithm:

2
REG. NO: 2117230070019

Program:
import java.util.Scanner;

public class PrimeValidator {


public static void main(String[] args) {
Scanner scannerInput = new Scanner(System.in);
System.out.print("Enter a number: ");
int userInput = scannerInput.nextInt();

if (isPrime(userInput)) {
System.out.println(userInput + " is a prime number.");
} else {
System.out.println(userInput + " is not a prime number.");
}
}

public static boolean isPrime(int value) {


if (value <= 1) {
return false;
}

for (int i = 2; i <= Math.sqrt(value); i++) {


if (value % i == 0) {
return false;
}
}
return true;
}
}

Output:

Enter a number: 17
17 is a prime number.
Enter a number: 16
16 is not a prime number.

Result:
EX NO:03
DATE: FIBONACCI SEQUENCE

Aim:

Algorithm :
REG. NO:2117230070019

Program:

import java.util.Scanner;

public class FibonacciSequence {


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

System.out.print("Enter the number of terms: ");

int terms = scanner.nextInt();

System.out.print("Fibonacci sequence up to " + terms + " terms: ");


for (int i = 0; i < terms; i++) {
System.out.print(fibonacci(i) + " ");
}
}

public static int fibonacci(int terms) {


if (terms <= 1) {
return terms;
}
return fibonacci(terms - 1) + fibonacci(terms - 2);
}
}

Output:

Enter the number of terms: 5


Fibonacci sequence up to 5 terms: 0 1 1 2 3

Result:
EX NO:04
DATE: CLASS WITH ATTRIBUTES

Aim:

Algorithm:
REG. NO:2117230070019

Program:

public class Vehicle {


// Attributes
private String type;
private String paintColor;
private boolean isOperational;

// Constructor
public Vehicle(String type, String paintColor) {
this.type = type;
this.paintColor = paintColor;
this.isOperational = false; // Vehicle is initially not operational
}

// Method to start the vehicle


public void start() {
if (!isOperational) {
isOperational = true;
System.out.println(type + " in " + paintColor + " has started.");
} else {
System.out.println(type + " is already running.");
}
}

// Method to stop the vehicle


public void stop() {
if (isOperational) {
isOperational = false;
System.out.println(type + " in " + paintColor + " has stopped.");
} else {
System.out.println(type + " is already stopped.");
}
}

// Main method to demonstrate the functionality


public static void main(String[] args) {
// Test Case 1
Vehicle vehicle1 = new Vehicle("Tesla Model S", "Red");
vehicle1.start();
vehicle1.stop();

// Test Case 2
Vehicle vehicle2 = new Vehicle("BMW X5", "Black");
vehicle2.start();
vehicle2.start();
vehicle2.stop();

// Test Case 3 done by 21172300700


Vehicle vehicle3 = new Vehicle("Audi Q7", "Blue");
vehicle3.stop();
vehicle3.start();
}
}

Output:

Tesla Model S in Red has


started.
Tesla Model S in Red has
stopped.
BMW X5 in Black has started.
BMW X5 is already running.
BMW X5 in Black has stopped.
Audi Q7 is already stopped.
Audi Q7 in Blue has started.

Result:
Aim:

Algorithm:

EX NO:05
DATE: SHAPE INHERITANCE IMPLEMENTATION
REG. NO : 2117230070019

Program:
// Base class GeometricFigure
abstract class GeometricFigure {
String figureColor;

// Constructor
public GeometricFigure(String figureColor) {
this.figureColor = figureColor;
}

// Abstract method to calculate the area


abstract double calculateArea();

// Method to display the figure's details


void display() {
System.out.println("Color: " + figureColor);
System.out.println("Area: " + calculateArea());
}
}

// Derived class RoundFigure


class RoundFigure extends GeometricFigure {
double circleRadius;

// Constructor
public RoundFigure(String figureColor, double circleRadius) {
super(figureColor);
this.circleRadius = circleRadius;
}

// Implementing the calculateArea method


@Override
double calculateArea() {
return Math.PI * circleRadius * circleRadius;
}
}

// Derived class Quadrilateral


class Quadrilateral extends GeometricFigure {
double figureLength;
double figureWidth;

// Constructor
public Quadrilateral(String figureColor, double figureLength, double figureWidth) {
super(figureColor);
this.figureLength = figureLength;
this.figureWidth = figureWidth;
}

// Implementing the calculateArea method


@Override
double calculateArea() {
return figureLength * figureWidth;
}
}

// Main class to demonstrate the functionality


public class FigureTest {
public static void main(String[] args) {
// Test Case 1
GeometricFigure roundFigure = new RoundFigure("Red", 5);
System.out.println("RoundFigure Details:");
roundFigure.display();

// Test Case 2
GeometricFigure quadrilateral = new Quadrilateral("Blue", 4, 6);
System.out.println("Quadrilateral Details:");
quadrilateral.display();

// Test Case 3
GeometricFigure anotherRoundFigure = new RoundFigure("Green", 7);
System.out.println("Another RoundFigure Details:");
anotherRoundFigure.display();
}
}

Output:

RoundFigure Details:
Color: Red
Area: 78.53981633974483
Quadrilateral Details:
Color: Blue
Area: 24.0
Another RoundFigure Details:
Color: Green
Area: 153.93804002589985

Result:
Aim:

EX NO: 06
DATE: BANKING SYSTEM

Algorithm :
REG. NO:2117230070019

Program:

// Interface for Account


interface Account {
void deposit(double amount);
void withdraw(double amount);
double getBalance();
}

// Interface for Transaction


interface Transaction {
void printStatement();
}

// Implementation of a Savings Account


class SavingsAccount implements Account, Transaction
{ private double balance;
private String accountHolder;

public SavingsAccount(String accountHolder, double initialBalance)


{ this.accountHolder = accountHolder;
this.balance = initialBalance;
}

@Override
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println(amount + " deposited.");
} else {
System.out.println("Invalid deposit amount.");
}
}

@Override
public void withdraw(double amount) {
if (amount > 0 && amount <= balance)
{ balance -= amount;
System.out.println(amount + " withdrawn.");
} else {
System.out.println("Invalid withdraw amount or insufficient balance.");
}
}

@Override
public double getBalance()
{ return balance;
}

@Override
public void printStatement() {
System.out.println("Account Holder: " + accountHolder);
System.out.println("Balance: " + balance);
}
}

// Main class to demonstrate the functionality


public class BankingSystem {
public static void main(String[] args) {
// Test Case 1: Create an account and perform some transactions
SavingsAccount account1 = new SavingsAccount("Alice", 1000);
System.out.println("Initial Statement:");
account1.printStatement();
account1.deposit(500);
account1.withdraw(200);
System.out.println("Final Statement:");
account1.printStatement();

// Test Case 2: Try to withdraw more than the balance


SavingsAccount account2 = new SavingsAccount("Bob", 300);
System.out.println("\nInitial Statement:");
account2.printStatement();
account2.withdraw(400);
System.out.println("Final Statement:");
account2.printStatement();

// Test Case 3: Invalid deposit and valid transaction


SavingsAccount account3 = new SavingsAccount("Charlie", 150);
System.out.println("\nInitial Statement:");
account3.printStatement();
account3.deposit(-50);
account3.deposit(100);
account3.withdraw(50);
System.out.println("Final Statement:");
account3.printStatement();
}
}

Output:

Initial Statement:
Account Holder: Alice
Balance: 1000.0
500.0 deposited.
200.0 withdrawn.
Final Statement:
Account Holder: Alice
Balance: 1300.0

Initial Statement:
Account Holder: Bob
Balance: 300.0
Invalid withdraw amount or insufficient balance.
Final Statement:
Account Holder: Bob
Balance: 300.0

Initial Statement:
Account Holder: Charlie
Balance: 150.0
Invalid deposit amount.
100.0 deposited.
50.0 withdrawn.
Final Statement:
Account Holder: Charlie
Balance: 200.0

EX NO:07 HANDLE EXCEPTIONS FOR DIVIDING A NUMBER


DATE: BY ZERO

Result:

Aim:
Algorithm:
REG. NO:2117230070019

Program:
import java.util.Scanner;

public class DivisionHandler {


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

// Test Case 1
System.out.println("Test Case 1:");
performDivision(10, 2);

// Test Case 2
System.out.println("\nTest Case 2:");
performDivision(10, 0);

// Test Case 3
System.out.println("\nTest Case 3:");
performDivision(20, 5);
}

public static void performDivision(int dividend, int divisor) {


try {
int result = dividend / divisor;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
}
}
}

Output:
Test Case 1:
Result: 5
Test Case 2:
Error: Cannot divide by zero.
Test Case 3:
Result: 4

Result:
Aim:

EX NO: 08 IMPLEMENT A MULTI-THREADED PROGRAM TO


DATE: SIMULATE A RACE BETWEEN TWO THREADS

Algorithm :
REG. NO:2117230070019

Program:
import java.util.Scanner;

class Contestant implements Runnable {


private String runnerName;
private int trackLength;

public Contestant(String runnerName, int trackLength) {


this.runnerName = runnerName;
this.trackLength = trackLength;
}

@Override
public void run() {
for (int i = 1; i <= trackLength; i++) {
System.out.println(runnerName + " ran " + i + " meters");
// Simulate running with a random sleep time
try {
Thread.sleep((int) (Math.random() * 100));
} catch (InterruptedException e) {
System.out.println(runnerName + " was interrupted.");
}
}
System.out.println(runnerName + " finished the race!");
}
}

public class CompetitionSimulation {


public static void main(String[] args) {
// Test Case 1: Race of 10 meters
System.out.println("Test Case 1: Race of 10 meters");
Thread contestant1 = new Thread(new Contestant("Runner1", 10));
Thread contestant2 = new Thread(new Contestant("Runner2", 10));
beginRace(contestant1, contestant2);

// Test Case 2: Race of 20 meters


System.out.println("\nTest Case 2: Race of 20 meters");
contestant1 = new Thread(new Contestant("Runner1", 20));
contestant2 = new Thread(new Contestant("Runner2", 20));
beginRace(contestant1, contestant2);

// Test Case 3: Race of 15 meters


System.out.println("\nTest Case 3: Race of 15 meters");
contestant1 = new Thread(new Contestant("Runner1", 15));
contestant2 = new Thread(new Contestant("Runner2", 15));
beginRace(contestant1, contestant2);
}
// Method to start the race and wait for both contestants to finish
public static void beginRace(Thread contestant1, Thread contestant2) {
contestant1.start();
contestant2.start();

try {
contestant1.join();
contestant2.join();
} catch (InterruptedException e) {
System.out.println("Race was interrupted.");
}

System.out.println("Race finished!\n");
}
}

Output:

Test Case 1: Race of 10


meters
Runner1 ran 1 meters
Runner2 ran 1 meters
Runner1 ran 2 meters
Runner2 ran 2 meters
... (intermediate output may
vary) ...
Runner1 finished the race!
Runner2 finished the race!
Race finished!

Test Case 2: Race of 20


meters
Runner1 ran 1 meters
Runner2 ran 1 meters
... (output continues for 20
meters) ...
Runner1 finished the race!
Runner2 finished the race!
Race finished!

Test Case 3: Race of 15


meters
Runner1 ran 1 meters
Runner2 ran 1 meters
... (output continues for 15
meters) ...
Runner1 finished the race!
Runner2 finished the race!
Race finished!

Result:

EXNO:09 IMPLEMENT DEPTH-FIRST AND BREADTH-FIRST


DATE: TRAVERSAL ALGORITHMS

Aim:

Algorithm:
REG. NO:2117230070019

Program:
import java.util.LinkedList;
import java.util.Queue;

// Generic class for a binary tree node


class Node<T> {
T value;
Node<T> leftChild;
Node<T> rightChild;

Node(T value) {
this.value = value;
this.leftChild = null;
this.rightChild = null;
}
}

// Generic class for a binary tree


class GenericTree<T> {
Node<T> mainNode;

GenericTree() {
mainNode = null;
}

// Depth-First Traversal - In-Order


void inOrderTraversal(Node<T> node) {
if (node != null) {
inOrderTraversal(node.leftChild);
System.out.print(node.value + " ");
inOrderTraversal(node.rightChild);
}
}

// Depth-First Traversal - Pre-Order


void preOrderTraversal(Node<T> node) {
if (node != null) {
System.out.print(node.value + " ");
preOrderTraversal(node.leftChild);

Output:

Test Case 1:
In-Order Traversal: 4 2 5 1 3
Pre-Order Traversal: 1 2 4 5 3
Post-Order Traversal: 4 5 2 3 1
Level-Order Traversal: 1 2 3 4 5

Test Case 2:
In-Order Traversal: D B E A C F Pre-Order
Traversal: A B D E C F Post-Order
Traversal: D E B F C A Level-Order
Traversal: A B C D E F

Test Case 3:
In-Order Traversal: 4.4 2.2 5.5 1.1 6.6 3.3 7.7
Pre-Order Traversal: 1.1 2.2 4.4 5.5 3.3 6.6 7.7
Post-Order Traversal: 4.4 5.5 2.2 6.6 7.7 3.3 1.1
Level-Order Traversal: 1.1 2.2 3.3 4.4 5.5 6.6 7.7

Result:
EX NO:10
DATE: CLIENT-SERVER CONNECTION USING SOCKETS.

Aim:

Algorithm :
REG. NO:2117230070019

Program:
import java.io.*;
import java.net.*;

public class BasicServer {


public static void main(String[] args) {
int serverPort = 12345;

try (ServerSocket serverConn = new ServerSocket(serverPort)) {


System.out.println("Server is listening on port " + serverPort);

while (true) {
Socket clientConn = serverConn.accept();
System.out.println("New client connected");

InputStream inputStream = clientConn.getInputStream();


BufferedReader inputReader = new BufferedReader(new InputStreamReader(inputStream));

OutputStream outputStream = clientConn.getOutputStream();


PrintWriter outputWriter = new PrintWriter(outputStream, true);

String clientMessage = inputReader.readLine();


System.out.println("Received from client: " + clientMessage);

outputWriter.println("Server received: " + clientMessage);


clientConn.close();
}
} catch (IOException ex) {
System.out.println("Server exception: " + ex.getMessage());
ex.printStackTrace();
}
}
}

import java.io.*;
import java.net.*;

public class BasicClient {


public static void main(String[] args) {
String serverAddress = "localhost";
int serverPort = 12345;

try (Socket clientConn = new Socket(serverAddress, serverPort)) {


OutputStream outputStream = clientConn.getOutputStream();
PrintWriter outputWriter = new PrintWriter(outputStream, true);

InputStream inputStream = clientConn.getInputStream();


BufferedReader inputReader = new BufferedReader(new InputStreamReader(inputStream));

// Sending message to server


String clientMessage = args.length > 0 ? args[0] : "Hello, Server!";
outputWriter.println(clientMessage);

// Reading response from server


String serverResponse = inputReader.readLine();
System.out.println("Server response: " + serverResponse);
} catch (UnknownHostException ex) {
System.out.println("Server not found: " + ex.getMessage());
} catch (IOException ex) {
System.out.println("I/O error: " + ex.getMessage());
}
}
}

Output:

Server is listening on port 12345


New client connected
Received from client: Hello, Server!
Server response: Server received: Hello, Server!
Server response: Server received: Greetings from Client!

Result:
EX NO: 11
DATE: CONNECTS TO A MYSQL DATABASE AND RETRIEVES
INFORMATION USING JDBC.

Aim:

Algorithm :
REG. NO:2117230070019

Program:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class DatabaseExample {


public static void main(String[] args) {
String databaseUrl = "jdbc:mysql://localhost:3306/testdb";
String dbUser = "root";
String dbPassword = "password"; // Change to your MySQL password

try {
// Establish connection
Connection dbConnection = DriverManager.getConnection(databaseUrl, dbUser, dbPassword);

// Create statement
Statement dbStatement = dbConnection.createStatement();

// Execute query
String sqlQuery = "SELECT * FROM users";
ResultSet resultSet = dbStatement.executeQuery(sqlQuery);

// Process result set


while (resultSet.next()) {
int userId = resultSet.getInt("id");
String userName = resultSet.getString("name");
String userEmail = resultSet.getString("email");

System.out.println("User ID: " + userId + ", Name: " + userName + ", Email: " + userEmail);
}

// Close connection
dbConnection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:

User ID: 1, Name: John Doe, Email: [email protected]

User ID: 2, Name: Jane Smith, Email: [email protected]

User ID: 3, Name: Alice Johnson, Email: [email protected]

query = "SELECT * FROM users WHERE id = 1"; ID: 1, Name:

John Doe, Email: [email protected]

String query = "SELECT * FROM users WHERE name LIKE 'Jane%'"; ID: 2,

Name: Jane Smith, Email: [email protected]

Result:

EX NO:12 MULTI-THREADED SERVER USING JAVA RMI

DATE:

Aim:
Algorithm:
REG. NO:2117230070019

Program:
import java.rmi.Remote;
import java.rmi.RemoteException;

public interface GreetingService extends Remote {


String greet(String name) throws RemoteException;
}
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class GreetingServiceImpl extends UnicastRemoteObject implements GreetingService {


protected GreetingServiceImpl() throws RemoteException {
super();
}

@Override
public synchronized String greet(String name) throws RemoteException {
System.out.println("Received request from client: " + name);
return "Hello, " + name + "!";
}
}
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class GreetingServer {


public static void main(String[] args) {
try {
GreetingService service = new GreetingServiceImpl();
Registry registry = LocateRegistry.createRegistry(1099);
registry.rebind("GreetingService", service);
System.out.println("Server started...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
EX NO:13 SIMPLE GUI APPLICATION TO CONVERT
DATE: TEMPERATURE BETWEEN CELSIUS AND FAHRENHEIT.
public class GreetingClient {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: java GreetingClient <name>");
return;
}
String name = args[0];
try {
Registry registry = LocateRegistry.getRegistry("localhost");
GreetingService service = (GreetingService) registry.lookup("GreetingService");
String response = service.greet(name);
System.out.println("Response from server: " + response);
} catch (Exception e) {
e.printStackTrace();
}
}
}

Output:
Server started…

java GreetingClient John

Received request from client: John

Response from server: Hello, John!

Result:

Aim:
Algorithm:

REG. NO:2117230070019

Program:

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

public class TempConverterApp extends JFrame {


private JTextField celsiusInput;
private JTextField fahrenheitInput;
private JButton convertToFahrenheitButton;
private JButton convertToCelsiusButton;

public TempConverterApp() {
// Create UI components
celsiusInput = new JTextField(10);
fahrenheitInput = new JTextField(10);
convertToFahrenheitButton = new JButton("Celsius to Fahrenheit");
convertToCelsiusButton = new JButton("Fahrenheit to Celsius");

// Set layout and add components


setLayout(new java.awt.GridLayout(3, 2));
add(new JLabel("Celsius:"));
add(celsiusInput);
add(new JLabel("Fahrenheit:"));
add(fahrenheitInput);
add(convertToFahrenheitButton);
add(convertToCelsiusButton);

// Add action listeners


convertToFahrenheitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
double celsius = Double.parseDouble(celsiusInput.getText());
double fahrenheit = celsius * 9 / 5 + 32;
fahrenheitInput.setText(String.format("%.2f", fahrenheit));
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "Please enter a valid number.");
}
}
});

convertToCelsiusButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
double fahrenheit = Double.parseDouble(fahrenheitInput.getText());
double celsius = (fahrenheit - 32) * 5 / 9;
celsiusInput.setText(String.format("%.2f", celsius));
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "Please enter a valid number.");
}
}
});
// Set frame properties
setTitle("Temperature Converter");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}

public static void main(String[] args) {


// Create and display the form
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TempConverterApp().setVisible(true);
}
});
}
}

Output:
Result:

EX NO:14 JAVAFX APPLICATION FOR A BASIC MEDIA PLAYER


DATE:
WITH PLAY, PAUSE AND STOP FUNCTIONALITIES.
Aim:

Algorithm:
REG. NO:2117230070019

Program:
package music_player;

import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class AudioPlayerApp {

public static void main(String[] args) throws


UnsupportedAudioFileException,
IOException, LineUnavailableException {

Scanner userInput = new


Scanner(System.in);

// Specify the actual path to your .wav file


File audioFile = new File("C:\\Users\\
MUGILAN\\Downloads\\bgm.tamil.wav");

if (!audioFile.exists()) {
System.out.println("Audio file not
found.");
return;
}

AudioInputStream audioStream =
AudioSystem.getAudioInputStream(audioFile)
;
Clip audioClip = AudioSystem.getClip();
audioClip.open(audioStream);

String userResponse = "";

while (!userResponse.equals("Q")) {
System.out.println("P = Play, S = Stop,
R = Reset, Q = Quit");
System.out.print("Enter your choice:
");

userResponse =
userInput.next().toUpperCase();

switch (userResponse) {
case ("P"):
audioClip.start();
break;
case ("S"):
audioClip.stop();
break;
case ("R"):

audioClip.setMicrosecondPosition(0);
break;
case ("Q"):
audioClip.close();
break;
default:
System.out.println("Not a valid
response");
}
}

userInput.close();
System.out.println("Byeeee!");
}
}

Output:

Result:
EX NO:15
GRAPHICAL APPLICATION USING JAVAFX THAT
DATE: INVOLVES REAL TIME DATA VISUALIZATION

Aim:

Algorithm:
REG. NO:2117230070019

Program:

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class DynamicLineChartApp extends Application {

private static final int MAX_POINTS = 50;


private XYChart.Series<Number, Number> dataSeries;
private int xValue = 0;
private double yValue = 0;

@Override
public void start(Stage primaryStage) {
// Setup the chart
final NumberAxis xAxis = new NumberAxis();
final NumberAxis yAxis = new NumberAxis();
xAxis.setLabel("Time (s)");
yAxis.setLabel("Value");

final LineChart<Number, Number> lineChart = new LineChart<>(xAxis, yAxis);


lineChart.setAnimated(false);
lineChart.setTitle("Real-Time Data Visualization");

dataSeries = new XYChart.Series<>();


lineChart.getData().add(dataSeries);

VBox root = new VBox(lineChart);


Scene scene = new Scene(root, 800, 600);

primaryStage.setTitle("Real-Time Data Visualization");


primaryStage.setScene(scene);
primaryStage.show();

// Start the data generator


startDataGeneration();
}
private void startDataGeneration() {
AnimationTimer timer = new AnimationTimer() {
@Override
public void handle(long now) {
addDataToSeries();
}
};
timer.start();
}

private void addDataToSeries() {


if (dataSeries.getData().size() > MAX_POINTS) {
dataSeries.getData().remove(0);
}

yValue = Math.sin(Math.toRadians(xValue));
dataSeries.getData().add(new XYChart.Data<>(xValue++, yValue));
}

public static void main(String[] args) {


launch(args);
}
}
Output:

Result:
EX.NO:16
MINI PROJECT
DATE:

Aim:

Description:

Sample program:
Copy and Paste the Code
Should not attach the Image for Code.

………………………………………..
Sample Output:

Screenshot (……………….)

Result:

You might also like