0% found this document useful (0 votes)
29 views19 pages

Kaushikoop 1

The document discusses two programs - the first moves selected elements from one ArrayList to another, and the second implements a phone book that allows users to lookup phone numbers based on names. It also includes code snippets and output for both programs.

Uploaded by

Harshu Vagadiya
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)
29 views19 pages

Kaushikoop 1

The document discusses two programs - the first moves selected elements from one ArrayList to another, and the second implements a phone book that allows users to lookup phone numbers based on names. It also includes code snippets and output for both programs.

Uploaded by

Harshu Vagadiya
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/ 19

KAUSHIK VADOLIYA Practical-6 220470107179

Practical-6
Program -1: Create ArrayList mover. In which selected
element of one list moved to another.
i.e.

Subject Selected Subject

Java

DAA

Maths-I

EME

Database

Lets move Java and DAA to selected subject

Subject Selected Subject

Maths-I Java

EME DAA

Database

CODE:
import java.util.ArrayList;

public class ArrayListMover {


public static void main(String[] args) {
// Initialize the ArrayLists
ArrayList<String> subjects = new ArrayList<>();
ArrayList<String> selectedSubjects = new ArrayList<>();

// Add subjects to the subjects ArrayList


subjects.add("Java");
subjects.add("Dm");
subjects.add("OS");
subjects.add("PEM");
subjects.add("COA");

Page | 30
KAUSHIK VADOLIYA Practical-6 220470107179
// Define the subjects to move
String[] subjectsToMove = {"COA", "PEM","OS"};

// Move the selected subjects


moveSelectedSubjects(subjects, selectedSubjects, subjectsToMove);

// Print the subjects


System.out.println("Subjects: " + subjects);
System.out.println("Selected Subjects: " + selectedSubjects);
}

public static void moveSelectedSubjects(ArrayList<String> subjects, ArrayList<String>


selectedSubjects, String[] subjectsToMove) {
for (String subject : subjectsToMove) {
if (subjects.contains(subject)) {
subjects.remove(subject);
selectedSubjects.add(subject);
}
}
}
}

OUTPUT:

Subjects: [Java, Dm]

Selected Subjects: [COA, PEM, OS]

Program -2: You are given a phone book that consists of


people's names and their phone number. After that you will
be given some person's name as query. For each query, print
the phone number of that person.
COAD:
import java.util.HashMap;
import java.util.Scanner;

public class PhoneBook {


public static void main(String[] args) {
// Create a HashMap to store the phone book entries
HashMap<String, String> phoneBook = new HashMap<>();

Page | 31
KAUSHIK VADOLIYA Practical-6 220470107179
// Scanner for user input
Scanner scanner = new Scanner(System.in);

// Add entries to the phone book


System.out.println("Enter the number of entries in the phone book:");
int n = scanner.nextInt();
scanner.nextLine(); // Consume the newline

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


System.out.println("Enter name:");
String name = scanner.nextLine();
System.out.println("Enter phone number:");
String phoneNumber = scanner.nextLine();
phoneBook.put(name, phoneNumber);
}

// Query the phone book


System.out.println("Enter the number of queries:");
int q = scanner.nextInt();
scanner.nextLine(); // Consume the newline

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


System.out.println("Enter name to query:");
String queryName = scanner.nextLine();
if (phoneBook.containsKey(queryName)) {
System.out.println(queryName + "=" + phoneBook.get(queryName));
} else {
System.out.println("Not found");
}
}

scanner.close();
}
}

OUTPUT:

Enter the number of entries in the phone book:

Enter name:

a1

Enter phone number:

Page | 32
KAUSHIK VADOLIYA Practical-6 220470107179
12547895648

Enter name:

a2

Enter phone number:

1236585965

Enter name:

a3

Enter phone number:

4585965231

Enter the number of queries:

Enter name to query:

a1

a1=12547895648

Enter name to query:

a4

Not found

Page | 33
KAUSHIK VADOLIYA Practical-7 220470107179

Practical-7
Program-1: Design program to print a string with TypeWriter
effect.
CODE:
public class TypeWriterEffect {
public static void main(String[] args) {
String text = "Hello, this is a TypeWriter effect!";
int delay = 100; // delay in milliseconds

typeWriter(text, delay);
}

public static void typeWriter(String text, int delay) {


for (int i = 0; i < text.length(); i++) {
System.out.print(text.charAt(i));
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("Thread was interrupted, Failed to complete
operation");
}
}
System.out.println(); // Print a new line at the end
}
}

OUTPUT:

Hello, this is a TypeWriter effect!

Program-2: Design PrettyPrinter in nonpremtive manner


using Thread.
CODE:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

Page | 34
KAUSHIK VADOLIYA Practical-7 220470107179
public class PrettyPrinter {
private final Lock lock = new ReentrantLock();

public void print(String message) {


lock.lock();
try {
System.out.println(message);
} finally {
lock.unlock();
}
}

public static void main(String[] args) {


PrettyPrinter printer = new PrettyPrinter();

Thread thread1 = new Thread(() -> {


printer.print("Thread 1: Hello!");
printer.print("Thread 1: This is a pretty printer.");
});

Thread thread2 = new Thread(() -> {


printer.print("Thread 2: Hi there!");
printer.print("Thread 2: Printing messages in a nice way.");
});

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

OUTPUT:

Thread 1: Hello!

Thread 1: This is a pretty printer.

Thread 2: Hi there!

Thread 2: Printing messages in a nice way.

Page | 35
KAUSHIK VADOLIYA Practical-8 220470107179

Practical-8
Program-1: Write a program to export book data in csv
format.
CODE:
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class BookExporter {


public static void main(String[] args) {
List<Book> books = new ArrayList<>();
books.add(new Book("1001", "Java Programming", "John Doe", 29.99));
books.add(new Book("1002", "Python Programming", "Jane Smith", 24.99));
books.add(new Book("1003", "Data Structures and Algorithms", "Alice Johnson",
39.99));

exportToCsv(books, "books.csv");
}

private static void exportToCsv(List<Book> books, String filename) {


try (FileWriter writer = new FileWriter(filename)) {
// Write CSV header
writer.append("ISBN,Title,Author,Price\n");

// Write CSV content


for (Book book : books) {
writer.append(String.join(",", book.getIsbn(), book.getTitle(),
book.getAuthor(), String.valueOf(book.getPrice())));
writer.append("\n");
}

System.out.println("CSV file exported successfully.");


} catch (IOException e) {
System.out.println("Error exporting CSV file: " + e.getMessage());
}
}

static class Book {


private String isbn;
private String title;
private String author;
private double price;

Page | 36
KAUSHIK VADOLIYA Practical-8 220470107179
public Book(String isbn, String title, String author, double price) {
this.isbn = isbn;
this.title = title;
this.author = author;
this.price = price;
}

public String getIsbn() {


return isbn;
}

public String getTitle() {


return title;
}

public String getAuthor() {


return author;
}

public double getPrice() {


return price;
}
}
}

OUTPUT:

CSV file exported successfully.


ISBN,Title,Author,Price
1001,Java Programming,John Doe,29.99
1002,Python Programming,Jane Smith,24.99
1003,Data Structures and Algorithms,Alice Johnson,39.99

Program-2: Implement file read, write and append operation.


CODE:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileReadWriteAppend {


public static void main(String[] args) {
// File path

Page | 37
KAUSHIK VADOLIYA Practical-8 220470107179
String filePath = "data.txt";

// Write to file
writeToFile(filePath, "Hello, world!");

// Read from file


String content = readFromFile(filePath);
System.out.println("File content: " + content);

// Append to file
appendToFile(filePath, "\nThis is a new line.\n this is file read");
content = readFromFile(filePath);
System.out.println("Updated file content: " + content);
}

private static void writeToFile(String filePath, String content) {


try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
writer.write(content);
System.out.println("Content written to file successfully.");
} catch (IOException e) {
System.out.println("Error writing to file: " + e.getMessage());
}
}

private static String readFromFile(String filePath) {


StringBuilder contentBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
contentBuilder.append(line).append("\n");
}
} catch (IOException e) {
System.out.println("Error reading from file: " + e.getMessage());
}
return contentBuilder.toString();
}

private static void appendToFile(String filePath, String content) {


try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true))) {
writer.append(content);
System.out.println("Content appended to file successfully.");
} catch (IOException e) {
System.out.println("Error appending to file: " + e.getMessage());
}
}
}

OUTPUT:

Content written to file successfully.


Page | 38
KAUSHIK VADOLIYA Practical-8 220470107179
File content: Hello, world!

Content appended to file successfully.

Updated file content: Hello, world!

This is a new line.

this is file read.

___________________________________________________________________________

Page | 39
KAUSHIK VADOLIYA Practical-9 220470107179

Practical-9
Program-1: Implement a utility to get content from input url.
COAD:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class URLContentReader {


public static void main(String[] args) {
String url = "https://www.example.com";

try {
String content = getContentFromUrl(url);
System.out.println("Content from URL: \n" + content);
} catch (IOException e) {
System.out.println("Error reading content from URL: " + e.getMessage());
}
}

private static String getContentFromUrl(String urlString) throws IOException {


URL url = new URL(urlString);
URLConnection connection = url.openConnection();
StringBuilder contentBuilder = new StringBuilder();

try (BufferedReader reader = new BufferedReader(new


InputStreamReader(connection.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
contentBuilder.append(line);
contentBuilder.append(System.lineSeparator());
}
}

return contentBuilder.toString();
}
}

OUTPUT:

Note: URLContentReader.java uses or overrides a deprecated API.

Note: Recompile with -Xlint:deprecation for details.

Page | 40
KAUSHIK VADOLIYA Practical-9 220470107179
Content from URL:

<!doctype html>

<html>

<head>

<title>Example Domain</title>

<meta charset="utf-8" />

<meta http-equiv="Content-type" content="text/html; charset=utf-8" />

<meta name="viewport" content="width=device-width, initial-scale=1" />

<style type="text/css">

body {

background-color: #f0f0f2;

margin: 0;

padding: 0;

font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans",


"Helvetica Neue", Helvetica, Arial, sans-serif;

div {

width: 600px;

margin: 5em auto;

padding: 2em;

background-color: #fdfdff;

border-radius: 0.5em;

Page | 41
KAUSHIK VADOLIYA Practical-9 220470107179
box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02);

a:link, a:visited {

color: #38488f;

text-decoration: none;

@media (max-width: 700px) {

div {

margin: 0 auto;

width: auto;

</style>

</head>

<body>

<div>

<h1>Example Domain</h1>

<p>This domain is for use in illustrative examples in documents. You may use this

domain in literature without prior coordination or asking for permission.</p>

<p><a href="https://www.iana.org/domains/example">More information...</a></p>

</div>

</body>

</html>

Page | 42
KAUSHIK VADOLIYA Practical-10 220470107179

Practical-10
Program-1: Write a javafx form for user signup which
includes username(Textfield), password(passwordfield),
gender(radiobutton),branch(combobox),address(textarea),h
obbies(checkbox). Create two buttons display value of user
data into a label. signup(button), clear(button)
CODE:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class UserSignupForm extends Application {

@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("User Signup Form");

// Create form components


TextField usernameTextField = new TextField("enter the user name");
PasswordField passwordField = new PasswordField();
ToggleGroup genderToggleGroup = new ToggleGroup();
RadioButton maleRadioButton = new RadioButton("Male");
maleRadioButton.setToggleGroup(genderToggleGroup);
RadioButton femaleRadioButton = new RadioButton("Female");
femaleRadioButton.setToggleGroup(genderToggleGroup);
ComboBox<String> branchComboBox = new ComboBox<>();
branchComboBox.getItems().addAll("Computer Science", "Electrical Engineering",
"Mechanical Engineering", "Civil Engineering");
TextArea addressTextArea = new TextArea();
CheckBox footballCheckBox = new CheckBox("Football");
CheckBox basketballCheckBox = new CheckBox("Basketball");
CheckBox cricketCheckBox = new CheckBox("Cricket");

// Create buttons
Button submitButton = new Button("Submit");
Button clearButton = new Button("Clear");

Page | 43
KAUSHIK VADOLIYA Practical-10 220470107179
// Create label to display user data
Label displayLabel = new Label();

// Button actions
submitButton.setOnAction(event -> {
// Gather user data
String username = usernameTextField.getText();
String password = passwordField.getText();
String gender = ((RadioButton)
genderToggleGroup.getSelectedToggle()).getText();
String branch = branchComboBox.getValue();
String address = addressTextArea.getText();
StringBuilder hobbies = new StringBuilder();
if (footballCheckBox.isSelected()) hobbies.append("Football, ");
if (basketballCheckBox.isSelected()) hobbies.append("Basketball, ");
if (cricketCheckBox.isSelected()) hobbies.append("Cricket, ");
// Display user data
displayLabel.setText("Username: " + username + "\nPassword: " + password +
"\nGender: " + gender +
"\nBranch: " + branch + "\nAddress: " + address + "\nHobbies: " +
hobbies.toString());
});

clearButton.setOnAction(event -> {
// Clear all fields
usernameTextField.clear();
passwordField.clear();
genderToggleGroup.selectToggle(null);
branchComboBox.getSelectionModel().clearSelection();
addressTextArea.clear();
footballCheckBox.setSelected(false);
basketballCheckBox.setSelected(false);
cricketCheckBox.setSelected(false);
displayLabel.setText("");
});

// Create layout
GridPane grid = new GridPane();
grid.setPadding(new Insets(20));
grid.setVgap(10);
grid.setHgap(10);
grid.add(new Label("Username:"), 0, 0);
grid.add(usernameTextField, 1, 0);
grid.add(new Label("Password:"), 0, 1);
grid.add(passwordField, 1, 1);
grid.add(new Label("Gender:"), 0, 2);
VBox genderBox = new VBox(5, maleRadioButton, femaleRadioButton);
grid.add(genderBox, 1, 2);
grid.add(new Label("Branch:"), 0, 3);
grid.add(branchComboBox, 1, 3);

Page | 44
KAUSHIK VADOLIYA Practical-10 220470107179
grid.add(new Label("Address:"), 0, 4);
grid.add(addressTextArea, 1, 4);
grid.add(new Label("Hobbies:"), 0, 5);
VBox hobbiesBox = new VBox(5, footballCheckBox, basketballCheckBox,
cricketCheckBox);
grid.add(hobbiesBox, 1, 5);

// Buttons
HBox buttonBox = new HBox(10, submitButton, clearButton);
grid.add(buttonBox, 1, 6);

// Display label
grid.add(displayLabel, 0, 7, 2, 1);

Scene scene = new Scene(grid, 400, 400);


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

public static void main(String[] args) {


launch(args);
}
}

OUTPUT:

Page | 45
KAUSHIK VADOLIYA Practical-10 220470107179
Program-2: Write a javafx program to move a circle from left
to right when navigation keys been clicked. when mouse
hovered over the circle then it change the color of circle.
CODE:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

public class CircleMovement extends Application {

private static final int CIRCLE_RADIUS = 50;


private static final int MOVE_DISTANCE = 10;

@Override
public void start(Stage primaryStage) {
Circle circle = new Circle(CIRCLE_RADIUS, Color.BLUE);
circle.setTranslateX(250);
circle.setTranslateY(250);

circle.setOnMouseEntered(e -> circle.setFill(Color.RED));


circle.setOnMouseExited(e -> circle.setFill(Color.BLUE));

Pane pane = new Pane(circle);

Scene scene = new Scene(pane, 500, 500);

scene.setOnKeyPressed(e -> {
if (e.getCode() == KeyCode.LEFT) {
circle.setTranslateX(circle.getTranslateX() - MOVE_DISTANCE);
} else if (e.getCode() == KeyCode.RIGHT) {
circle.setTranslateX(circle.getTranslateX() + MOVE_DISTANCE);
} else if (e.getCode() == KeyCode.UP) {
circle.setTranslateY(circle.getTranslateY() - MOVE_DISTANCE);
} else if (e.getCode() == KeyCode.DOWN) {
circle.setTranslateY(circle.getTranslateY() + MOVE_DISTANCE);
}
});

primaryStage.setScene(scene);
primaryStage.setTitle("Circle Movement");
primaryStage.show();
}

Page | 46
KAUSHIK VADOLIYA Practical-10 220470107179

public static void main(String[] args) {


launch(args);
}
}

OUTPUT:

Program-3: Write a javafx program to play mp3 and mp4


files.
CODE:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;

Page | 47
KAUSHIK VADOLIYA Practical-10 220470107179
import javafx.stage.Stage;

import java.io.File;

public class MediaExample extends Application {

@Override
public void start(Stage primaryStage) {
String mp3File = "sample.mp3";
String mp4File = "sample.mp4";

Media mp3 = new Media(new File(mp3File).toURI().toString());


MediaPlayer mediaPlayer = new MediaPlayer(mp3);

MediaView mediaView = new MediaView(mediaPlayer);

Media mp4 = new Media(new File(mp4File).toURI().toString());


MediaPlayer videoPlayer = new MediaPlayer(mp4);
MediaView videoView = new MediaView(videoPlayer);

StackPane root = new StackPane();


root.getChildren().addAll(mediaView, videoView);

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

primaryStage.setTitle("Media Player Example");


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

mediaPlayer.play();
videoPlayer.play();
}

public static void main(String[] args) {


launch(args);
}
}

Page | 48

You might also like