0% found this document useful (0 votes)
2 views7 pages

Java Solutions

The document provides solutions to ten Java programming problems, covering topics such as file input/output, data filtering, exception handling, and data structure management. Each problem includes sample code demonstrating the implementation of the solution. The problems range from basic file operations to more complex tasks like palindrome checking and merging data structures.

Uploaded by

DARK NIGHT
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)
2 views7 pages

Java Solutions

The document provides solutions to ten Java programming problems, covering topics such as file input/output, data filtering, exception handling, and data structure management. Each problem includes sample code demonstrating the implementation of the solution. The problems range from basic file operations to more complex tasks like palindrome checking and merging data structures.

Uploaded by

DARK NIGHT
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

Java Programming

Solutions to All 10 Problems

Problem 1: File Input and Output Using Byte Streams


Reads a filename and string from user, writes using FileOutputStream, reads back using FileInputStream, and
prints the content.

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

public class Problem1 {


public static void main(String[] args) throws IOException {
Scanner sc = new Scanner([Link]);
String fileName = [Link]().trim();
String content = [Link]();

// Write to file
FileOutputStream fos = new FileOutputStream(fileName);
[Link]([Link]());
[Link]();

// Read back from file


FileInputStream fis = new FileInputStream(fileName);
byte[] buffer = new byte[[Link]()];
[Link](buffer);
[Link]();

[Link](new String(buffer));
}
}

Problem 2: Filter Scores Divisible by a Number


Takes an ArrayList of scores and removes all elements divisible by a given number, then prints the filtered list.

import [Link].*;

public class Problem2 {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]([Link]().trim());

ArrayList<Integer> scores = new ArrayList<>();


String[] parts = [Link]().trim().split("\\s+");
for (String p : parts) [Link]([Link](p));

int divisor = [Link]([Link]().trim());

[Link](score -> score % divisor == 0);

[Link](scores);
}
}

Problem 3: Lottery Ticket Validation – Perfect Number Check


Validates whether a lottery ticket number is a perfect number. Throws a custom NotPerfectNumberException if it
is not, otherwise prints the reverse of the number.

import [Link];

class NotPerfectNumberException extends Exception {


public NotPerfectNumberException(String message) {
super(message);
}
}

public class Problem3 {

static boolean isPerfect(int n) {


if (n < 2) return false;
int sum = 1;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
sum += i;
if (i != n / i) sum += n / i;
}
}
return sum == n;
}

static int reverse(int n) {


int rev = 0;
while (n > 0) {
rev = rev * 10 + n % 10;
n /= 10;
}
return rev;
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
int ticket = [Link]([Link]().trim());
try {
if (!isPerfect(ticket))
throw new NotPerfectNumberException(
"Ticket number is not perfect");
[Link](reverse(ticket));
} catch (NotPerfectNumberException e) {
[Link]([Link]());
}
}
}

Problem 4: Employee Records Backup Using Byte Streams


Reads employee data from a source file, copies it to a backup file using FileInputStream and FileOutputStream,
then displays the backed-up content.
import [Link].*;
import [Link];

public class Problem4 {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
String source = [Link]().trim();
String backup = [Link]().trim();

try (FileInputStream fis = new FileInputStream(source);


FileOutputStream fos = new FileOutputStream(backup)) {

byte[] buffer = new byte[1024];


int bytesRead;
while ((bytesRead = [Link](buffer)) != -1) {
[Link](buffer, 0, bytesRead);
}

// Read and display backup content


FileInputStream verify = new FileInputStream(backup);
byte[] content = new byte[[Link]()];
[Link](content);
[Link]();
[Link](new String(content));

} catch (FileNotFoundException e) {
[Link]("Source file not found");
} catch (IOException e) {
[Link]();
}
}
}

Problem 5: Find Common Prefix Among Strings


Takes an ArrayList of strings and finds the longest common prefix. Prints the prefix, or 'No common prefix found'
if none exists.

import [Link].*;

public class Problem5 {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]([Link]().trim());

String[] parts = [Link]().trim().split("\\s+");


ArrayList<String> list = new ArrayList<>([Link](parts));

if ([Link]()) {
[Link]("No common prefix found");
return;
}

String prefix = [Link](0);


for (int i = 1; i < [Link](); i++) {
while (![Link](i).startsWith(prefix)) {
prefix = [Link](0, [Link]() - 1);
if ([Link]()) {
[Link]("No common prefix found");
return;
}
}
}
[Link](prefix);
}
}

Problem 6: Queue Management System for a Service Center


Menu-driven program that supports Enqueue, Dequeue, Display Queue, and Exit operations using a
LinkedList-based Queue.

import [Link].*;

public class Problem6 {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
Queue<String> queue = new LinkedList<>();

while (true) {
[Link]("\n1. Enqueue");
[Link]("2. Dequeue");
[Link]("3. Display Queue");
[Link]("4. Exit");
[Link]("Enter choice: ");
int choice = [Link]([Link]().trim());

switch (choice) {
case 1:
[Link]("Enter name: ");
String name = [Link]().trim();
[Link](name);
[Link](name + " added to the queue.");
break;
case 2:
if ([Link]())
[Link]("Queue is empty.");
else
[Link]("Serving: " + [Link]());
break;
case 3:
if ([Link]())
[Link]("Queue is empty.");
else
[Link]("Current Queue: " + queue);
break;
case 4:
[Link]("Exiting...");
return;
default:
[Link]("Invalid choice.");
}
}
}
}
Problem 7: Merge Two Store Inventories (HashMaps)
Reads two HashMaps of product IDs and prices, merges them into a single HashMap, and prints entries in
key-sorted order.

import [Link].*;

public class Problem7 {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
HashMap<Integer, Integer> map1 = new HashMap<>();
HashMap<Integer, Integer> map2 = new HashMap<>();

int n1 = [Link]([Link]().trim());
for (int i = 0; i < n1; i++) {
String[] p = [Link]().trim().split("\\s+");
[Link]([Link](p[0]), [Link](p[1]));
}

int n2 = [Link]([Link]().trim());
for (int i = 0; i < n2; i++) {
String[] p = [Link]().trim().split("\\s+");
[Link]([Link](p[0]), [Link](p[1]));
}

// Merge: map2 values override map1 on duplicate keys


HashMap<Integer, Integer> merged = new HashMap<>(map1);
[Link](map2);

TreeMap<Integer, Integer> sorted = new TreeMap<>(merged);


for ([Link]<Integer, Integer> entry : [Link]()) {
[Link]([Link]() + " " + [Link]());
}
}
}

Problem 8: Square Root Calculator with Exception Handling


Calculates the square root of a given integer. Handles negative numbers and invalid (non-integer) input with
appropriate exception messages.

import [Link];

public class Problem8 {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
String input = [Link]().trim();
try {
int number = [Link](input);
if (number < 0) {
[Link](
"Error: Square root of a negative number is not possible");
} else {
[Link]("%.2f%n", [Link](number));
}
} catch (NumberFormatException e) {
[Link]("Error: Invalid input");
}
}
}

Problem 9: Palindrome Check Using Lambda Expression


Uses a lambda expression (via a functional interface) to check whether a given string is a palindrome in a
case-insensitive manner.

import [Link];
import [Link];

public class Problem9 {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
String input = [Link]().trim();

Predicate<String> isPalindrome = s -> {


String lower = [Link]();
String reversed = new StringBuilder(lower).reverse().toString();
return [Link](reversed);
};

if ([Link](input))
[Link]("Palindrome");
else
[Link]("Not Palindrome");
}
}

Problem 10: Employee Records Backup (Byte Streams) – Extended


Same backup requirement as Problem 4 but structured as a reusable static method. Demonstrates clean
separation of file-copy logic and error handling.

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

public class Problem10 {

static void backupFile(String source, String destination)


throws IOException {
try (FileInputStream fis = new FileInputStream(source);
FileOutputStream fos = new FileOutputStream(destination)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = [Link](buffer)) != -1) {
[Link](buffer, 0, bytesRead);
}
}
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
String source = [Link]().trim();
String destination = [Link]().trim();

try {
backupFile(source, destination);

// Verify: read and display backup content


FileInputStream fis = new FileInputStream(destination);
byte[] content = new byte[[Link]()];
[Link](content);
[Link]();
[Link](new String(content));

} catch (FileNotFoundException e) {
[Link]("Source file not found");
} catch (IOException e) {
[Link]();
}
}
}

You might also like