0% found this document useful (0 votes)
3 views55 pages

Java Assign2

The document outlines multiple programming assignments involving Java packages, interfaces, exception handling, and collections. Each assignment includes code snippets for creating classes, methods, and main classes to demonstrate functionality such as shape calculations, multi-interface implementation, arithmetic operations, and student management using ArrayLists. The document serves as a comprehensive guide for implementing various object-oriented programming concepts in Java.

Uploaded by

pratikgarad98
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)
3 views55 pages

Java Assign2

The document outlines multiple programming assignments involving Java packages, interfaces, exception handling, and collections. Each assignment includes code snippets for creating classes, methods, and main classes to demonstrate functionality such as shape calculations, multi-interface implementation, arithmetic operations, and student management using ArrayLists. The document serves as a comprehensive guide for implementing various object-oriented programming concepts in Java.

Uploaded by

pratikgarad98
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

Name:- Shraddha Dilip Gosavi

Div :- A
RollNo :- 2501064
Assignment 2
Interfaces, Packages and Exception Handling & The Collection Framework

1. Create a package ShapePkg. In this package, write an interface Shape having methods area() and
perimeter(). Create two classes Circle and Rectangle that implement this interface and override its
methods. Write another class with main() method to create objects of both classes, accept input
using Scanner, and display the results.

Code :-

//

package ShapePkg;

public interface Shape {

double area();

double perimeter();

} //

package ShapePkg;

public class Circle implements Shape

public double radius;

public Circle(double radius)

[Link]=radius;

public double area()

return [Link]*radius*radius;
}

public double perimeter()

return 2*[Link]*radius;

} //

package ShapePkg; public class

Rectangle implements Shape

double length;

double width;

public Rectangle(double length,double width)

[Link]=length;

[Link]=width;

public double area()

return length*width;

public double perimeter()

return 2*(length+width);

//
package ShapePkg; import

[Link]; import

[Link]; import

[Link]; public

class TestShape

public static void main(String[] args)

Scanner sc=new Scanner([Link]);

[Link]("-----Circle-----");

[Link]("Enter Radius of Circle :");

double rd=[Link]();

Circle c=new Circle(rd);

[Link]("Area of Circle :"+[Link]());

[Link]("Perimeter of Circle :"+[Link]());

[Link]("-----Rectangle-----");

[Link]("Enter length of rectangle :");

double l=[Link]();

[Link]("Enter Width of rectangle :");

double w=[Link]();

Rectangle r=new Rectangle(l,w);

[Link]("Area of Rectangle :"+[Link]());

[Link]("Perimeter of Rectangle :"+[Link]());

}
Output :-

2. Create a package MultiInterfacePkg. Define two interfaces Printable and Showable with methods

print() and show(). Create a class Document that implements both interfaces and provides method

definitions. Write a main class to create an object of Document and call both methods. Code :-

package MultiInterfacePkg; public interface Printable

void print();

} //

package MultiInterfacePkg; public

interface Showable

void show();

} //

package MultiInterfacePkg; public class Document


implements Printable,Showable

public void print()

[Link]("This is Print() method.");

public void show()


{

[Link]("This is show() method.");

} //

package MultiInterfacePkg;

import MultiInterfacePkg.*;

public class MultiInterfaceMain

public static void main(String[] args)

Document d=new Document();

[Link]();

[Link]();

Output :-

3. Create a package MathOperationsPkg. In this package, write a class Calculator with methods for
addition, subtraction, multiplication, and division. Create another class in a different package to
import this package and use its methods. Write the main method to perform operations based on
user input. Code :-

package MathOperationsPkg;

public class Calculator

public double addition(double a,double b)

return a+b;

}
public double subtraction(double a,double b)

return a-b;

public double multiplication(double a,double b)

return a*b;

public double division(double a,double b)

return a/b;

} //

package MathOperationsPkg; import


MathOperationsPkg.*;
import [Link].*; public

class CalculatorDemo

public static void main(String[] args)

Scanner sc=new Scanner([Link]);

Calculator c=new Calculator(); [Link]("Enter 1st

Number :");

int a=[Link]();

[Link]("Enter 2nd Number :");

int b=[Link](); [Link]("[Link]");

[Link]("[Link]");

[Link]("[Link]");

[Link]("[Link]"); [Link]("Enter

Your Choice :");


int ch=[Link]();

switch(ch)

case 1:

[Link]("Result :"+[Link](a,b));

break;

case 2:

[Link]("Result :"+[Link](a,b));

break;

case 3:

[Link]("Result :"+[Link](a,b));

break;

case 4:

[Link]("Result :"+[Link](a,b));

break;

default:

[Link]("Invalid Choice!");

[Link]();

Output :-
4. Create a package StudentPkg. Define a class Student with variables having different access
modifiers (public, protected, default). Create another package and write a class to access these
variables. Write a main method to demonstrate which members are accessible and which are not.
Code :- package StudentPkg; public class Student

public String name="Divya"; protected int

age=20;

String course="MCA";

} //

package StudentPkg;

import StudentPkg.*; public

class TestStudent

public static void main(String[] args)

Student s=new Student();

[Link]("Accessing From different Package :");

[Link]("Name (public):"+[Link]);

[Link]("Age (protected):"+[Link]);

[Link]("Course (default):"+[Link]);

[Link]("Access protected using inheritance.");

}}

Output :-
5. Create a package UtilityPkg. Write a class StringUtility with methods reverse() and toUpperCase().

Create another class that imports this package using both explicit import and wildcard import. Write

a main method to call these methods and display output. Code :- package UtilityPkg; public class

StringUtility

public String reverse(String str)

String rev="";

for(int i=[Link]()-1;i>=0;i--)

rev+=[Link](i);

return rev;

public String UpperCase(String str)

return [Link]();

//

package UtilityPkg;

import UtilityPkg.*;

import [Link].*;

public class TestUtility

public static void main(String[] args)

Scanner sc=new Scanner([Link]);

StringUtility su=new StringUtility();

[Link]("Enter a String :");

String str=[Link]();
[Link]("Reversed String :"+[Link](str));

[Link]("Uppercase String :"+[Link](str));

Output :-

6. Create a package StudentDataPkg. Write a class Student to accept name, roll number, and marks
of 3 subjects using Scanner. Calculate total and average marks. Write a main class to create object
and display student details. Code :- package StudentDataPkg;

import [Link].*; public

class StudentData

String name; int

rollno; double

m1,m2,m3;

double total,average;

public void accept()

Scanner sc=new Scanner([Link]); [Link]("Enter RollNo :");

rollno=[Link]();

[Link]("Enter Name :");

name=[Link]();

[Link]("Enter Marks Of 3 Subject :");

m1=[Link]();

m2=[Link](); m3=[Link]();

}
public void calculate()

total=m1+m2+m3;

average=total/3;

public void display()

[Link]("Student Details");

[Link]("Roll No :"+rollno);

[Link]("Name :"+name);

[Link]("Total Marks :"+total);

[Link]("Average Marks :"+average);

package StudentDataPkg;

import StudentDataPkg.*; public

class StudentTest

public static void main(String[] args)

StudentData sd=new StudentData();

[Link]();

[Link](); [Link]();

Output :-
7. Create a package ExceptionPkg. Write a class Division to perform division of two numbers. Handle
ArithmeticException using try-catch and use finally block to display a message. Write a main class to
test the program with user input. Code :- package ExceptionPkg;

public class Division

public void divide(int a,int b)

try

int result = a/b;

[Link]("Result :"+result);

catch(ArithmeticException ae)

[Link]("Error: Cannot divide by Zero");

finally

[Link]("Finally Block Executed");

}
} //

package ExceptionPkg; import

ExceptionPkg.*;

import [Link].*; public

class TestDivision

public static void main(String[] args)

Division d=new Division();

Scanner sc=new Scanner([Link]); [Link]("Enter 1st

Number :");

int n1=[Link]();

[Link]("Enter 2nd Number :");

int n2=[Link]();

[Link](n1,n2);

Output :-

8. Create a package AgePkg. Write a class AgeValidator with a method checkAge(int age) that throws
an exception if age is less than 18 using throw. Use throws in method declaration. Write a main class
to call this method and handle the exception. Code :- package AgePkg; public class AgeValidator

{
public void checkAge(int age) throws Exception

if(age<18)

throw new Exception("Age is less than 18. Not Eligible");

} //
package AgePkg;

import [Link].*; public


class TestAge

public static void main(String[] args)

Scanner sc=new Scanner([Link]);

AgeValidator a=new AgeValidator();

[Link]("Enter Age :");

int age=[Link]();

try

[Link](age);

catch(Exception e)

[Link]("Exception :"+[Link]());

Output :-
9. Create a package EmployeePkg. Define a user-defined exception class InvalidSalaryException.
Write a class Employee that throws this exception if salary is below a given limit. Write a main class
to accept salary input and handle the exception with a proper message. Code :- package
EmployeePkg;

public class InvalidSalaryException extends Exception

public InvalidSalaryException(String msg)

super(msg);

//

package EmployeePkg; public

class Employee

double salary;

final double min_salary=10000;

public void setSalary(double salary) throws InvalidSalaryException

if(salary<min_salary)

throw new InvalidSalaryException("Salary is below minimum limit");

else

[Link]=salary;
[Link]("Salary Accepted :"+salary);

} //

package EmployeePkg;

import [Link].*;

import EmployeePkg.*; public

class TestEmployee

public static void main(String[] args)

Scanner sc=new Scanner([Link]);

Employee e=new Employee();

[Link]("Enter Salary :");

double salary=[Link]();

try

[Link](salary);

catch(InvalidSalaryException ee)

[Link]("Exception :"+[Link]());

Output :-
10. Create a package ArrayListPkg. In this package, write a class Student with attributes id, name, and
marks. Create another class StudentManager that uses ArrayList to store multiple student objects.
Include methods to add, remove, search, and display students. Write a main class to perform all
operations using user input and display results. Code :- package ArrayListPkg; public class Student

int id;

String name;

double marks;

public Student(int id, String name, double marks)

super();

[Link] = id; [Link]

= name; [Link]

= marks;

package ArrayListPkg; import

[Link]; public

class StudentManager

ArrayList<Student> a= new ArrayList<>();

public void addStudent(Student s)

[Link](s);
[Link]("Student Added");

public void removeStudent(int id)

boolean found=false;

for(Student s:a)

if([Link]==id)

[Link](s);

[Link]("Student Removed..");
found=true;

break;

if(!found)

[Link]("Student Not Found..");

public void searchStudent(int id)

boolean found=false;

for(Student s:a)

if([Link]==id)

[Link]("Id :"+[Link]+" Name :"+[Link]+"


Marks :"+[Link]);
found=true;

break;

if(!found)

[Link]("Student Not Found..");

public void displayAll()

if([Link]())

[Link]("No Student Available");

else

for(Student s:a)

[Link]("Id :"+[Link]+" Name :"+[Link]+"


Marks :"+[Link]);

} //

package ArrayListPkg;

import ArrayListPkg.*;

import [Link].*; public

class StudentMain

{
public static void main(String[] args)

Scanner sc=new Scanner([Link]);

StudentManager sm=new StudentManager();

int ch;

do {

[Link]("1:Add Student");

[Link]("2:Remove Student");

[Link]("3:Search Student");

[Link]("4:Display All");

[Link]("5:Exit");

[Link]("Enter Your Choice :");

ch=[Link]();

switch(ch)

case 1:

[Link]("Enter Id :");

int id=[Link]();

[Link]("Enter Name :");

String name = [Link]();

[Link]("Enter Marks :");

double marks=[Link]();

[Link](new Student(id, name, marks));

break;

case 2:

[Link]("Enter Id to Remove :");

[Link]([Link]());
break;

case 3:

[Link]("Enter Id to Search :");

[Link]([Link]());

break;

case 4:

[Link]();

break;

case 5:

[Link]("Exit");

break;

default:

[Link]("Invalid Choice...");

while(ch!=5);

Output :-
11. Create a package ArrayListSortPkg. Write a class Employee with attributes id, name, and salary.
Use ArrayList to store employee objects and implement sorting based on salary using Comparator.
Also filter employees with salary above a given value. Write a main class to demonstrate sorting and
filtering operations.
Code :- package

ArrayListSortPkg; public

class Employee

int id; String

name; double salary;

public Employee(int id, String name, double salary) {


super();

[Link] = id;

[Link] = name;

[Link] = salary;

public void display()

[Link]("Employee Id :"+id+"\nEmployee Name :"

+name+"\nEmployee Salary :"+salary);

} //

package ArrayListSortPkg;

import [Link]; import

[Link]; import

[Link];

public class EmployeeManager

ArrayList<Employee> list=new ArrayList<Employee>();

public void addEmployee(Employee e)

[Link](e);

public void sortBySalay()

[Link](list,new Comparator<Employee>()

{ @Override
public int compare(Employee e1, Employee e2) { return
[Link]([Link], [Link]);

});

public void filterBySalary(double limit)

[Link]("Employees with salary above "+limit+":");

for(Employee e:list)

if([Link] >limit)

[Link]();

public void displayAll()

for(Employee e:list)

[Link]();

} //

package ArrayListSortPkg;

import [Link]; import

ArrayListSortPkg.*; public class

EmployeeMain
{

public static void main(String[] args)

Scanner sc=new Scanner([Link]);

EmployeeManager em=new EmployeeManager();

[Link]("Enter No of Employees :");

int n=[Link]();

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

[Link]("Enter Details of Employee "+(i+1));

[Link]("Employee Id :");

int id=[Link]();

[Link]("Employee Name :"); String name=[Link]();

[Link]("Employee Salary :");

double Salary=[Link]();

[Link](new Employee(id, name, Salary));

[Link]("\n-----Before Sorting-----");

[Link]();

[Link]();

[Link]("\n-----After Sorting-----");

[Link]();

[Link]("Enter Salary limit to filter:");

double limit = [Link]();

[Link](limit);

}
Output :-

12. Create a package LinkedListPkg. Write a class Task with attributes taskId and taskName. Create a
class TaskManager that uses LinkedList to manage tasks. Implement methods to add tasks at
beginning/end, remove tasks, and display tasks. Write a main class to demonstrate all operations
using user input. Code :- package LinkedListPkg; public class Task

int taskId;

String taskName;

public Task(int taskId, String taskName) {

super();

[Link] = taskId;

[Link] = taskName;

}
public void display()

[Link]("Task ID :"+taskId+", TaskName :"+taskName);

} //

package LinkedListPkg; import

[Link]; public

class TaskManager

LinkedList<Task> list=new LinkedList<Task>();

public void addFirst(Task t)

[Link](t);

[Link]("Task added at beginning..");

public void addLast(Task t)

[Link](t);

[Link]("Task added at last..");

public void removeTask(int taskId)

boolean found=false;

for(Task t:list)

if([Link]==taskId)
{

[Link](t);

[Link]("Task removed..");

found=true;

break;

if(!found)

[Link]("Task not found..");

public void displayTask()

{ if([Link]())

[Link]("No Task Available..");

else

for(Task t:list)

[Link]();

} //

package LinkedListPkg; import

LinkedListPkg.*; import
[Link]; public class

TaskMain

public static void main(String[] args) {

Scanner sc=new Scanner([Link]);

TaskManager t=new TaskManager();

int ch;

do {

[Link]("1:Add Task at Beginning");

[Link]("2:Add Task at end");

[Link]("[Link] Task");

[Link]("[Link] Task");

[Link]("[Link]");

[Link]("Enter Your Choice :");

ch=[Link]();

switch(ch)

case 1:

[Link]("Enter Task Id :");

int id1=[Link]();

[Link]("Enter Task Name :");

String name1=[Link]();

[Link](new Task(id1, name1));

break;

case 2:

[Link]("Enter Task Id :");

int id2=[Link]();

[Link]("Enter Task Name :");

String name2=[Link]();
[Link](new Task(id2, name2));

break;

case 3:

[Link]("Enter task Id to remove :");

int id=[Link]();

[Link](id);

break;

case 4:

[Link]();

break;

case 5:

[Link]("Exit..");

break;

default:

[Link]("Invalid Choice..");

while(ch!=5);

Output :-
13. Create a package QueuePkg. Write a class QueueDemo that uses LinkedList to simulate queue
operations like enqueue, dequeue, and peek. Handle underflow condition using exception
handling. Write a main class to test queue operations. Code :-
package QueuePkg;

import [Link];

public class QueueDemo

LinkedList<Integer> queue=new LinkedList<Integer>();

public void enqueue(int data)

{
[Link](data);

[Link]("Enqueued Data :"+data);

public void dequeue()

try

if([Link]())

throw new Exception("Queue Underflow");

int removed=[Link]();

[Link]("Dequeued :"+removed);

catch(Exception e) {

[Link]([Link]());

public void peek()

{ try

if([Link]())

throw new Exception("Queue is Empty.");

[Link]("Front Element :"+[Link]());

catch(Exception e)
{

[Link]([Link]());

public void display()

if([Link]())

[Link]("Queue is empty.");

else

[Link]("Queue :"+queue);

} //

package QueuePkg; import


QueuePkg.*;

import [Link];

public class TestQueue {

public static void main(String[] args)

Scanner sc=new Scanner([Link]);

QueueDemo q=new QueueDemo();

int ch;

do

{
[Link]("1:Enqueue.");

[Link]("2:Dequeue.");

[Link]("3:Peek");

[Link]("4:Display.");

[Link]("5:Exit.");

[Link]("Enter Choice :");

ch=[Link]();

switch(ch)

case 1:

[Link]("Enter Element to Enqueue :");

int data=[Link]();

[Link](data);

break;

case 2:

[Link]();

break;

case 3:

[Link]();

break;

case 4:

[Link]();

break;

case 5:

[Link]("Exit");

break;

default:

[Link]("Invalid Choice!");

}
}while(ch!=5);

Output :-

14. Create a package VectorPkg. Write a class Product with attributes id, name, and price. Use Vector
to store product objects and demonstrate thread-safe operations by adding and removing elements.
Write a main class to perform operations and display results. Code :- package VectorPkg; public class
Product
{

int id;

String name; double


price

public Product(int id, String name, double price)

super();
[Link] = id;

[Link] = name;

[Link] = price;

public void display()

[Link]("Product Id :"+id+", Product Name :"+name+", Price :"+price);

} //

package VectorPkg;

import [Link]; public


class ProductManager
{

Vector<Product> v=new Vector<Product>();

public synchronized void addProduct(Product p)

[Link](p);

[Link]("Product Added..");

public synchronized void removeProduct(int id)

boolean found=false; for(Product


p:v)

if([Link]==id)

{
[Link](p);

found=true;

[Link]("Product removed..");

break;

if(!found)

[Link]("Product not found");

public void displayAll()

if([Link]())

[Link]("No Products available..");

else

for(Product p:v)

[Link]();

//

package VectorPkg;

import [Link];
import VectorPkg.*; public

class TestProduct {

public static void main(String[] args)

Scanner sc=new Scanner([Link]);

ProductManager pm=new ProductManager();

int ch;

do

[Link]("1:Add Product");

[Link]("2:Remove product");

[Link]("3:Display product");

[Link]("4:Exit");

[Link]("Enter Your Choice :");

ch=[Link]();

switch (ch) {

case 1:

[Link]("Enter ID: ");

int id = [Link]();

[Link]();

[Link]("Enter Name: ");

String name = [Link]();

[Link]("Enter Price: "); double price

= [Link](); [Link](new

Product(id, name, price)); break;

case 2:

[Link]("Enter ID to remove: ");

[Link]([Link]());
break;

case 3:

[Link]();
break;

case 4:

[Link]("Exiting...");

break;

default:

[Link]("Invalid Choice.");

while(ch!=4);

Output :-
15. Create a package StackPkg. Write a class StackDemo that uses Stack to evaluate a postfix
expression. Implement push, pop, and peek operations and handle empty stack using exception
handling. Write a main class to input expression and display result. Code :- package StackPkg;
import [Link]; public class StackDemo

Stack<Integer> s=new Stack<Integer>();

public void push(int value)

[Link](value);

public int pop()

{
if([Link]())

throw new RuntimeException("Stack is empty!!");

return [Link]();

public int evaluatePostfix(String exp)

try

for(int i=0;i<[Link]();i++)

char ch=[Link](i);

if([Link](ch))

push(ch-'0');

else

int b=pop();

int a=pop();

switch(ch)

case '+':

push(a+b);

break;
case '-':

push(a-b);

break;

case '*':

push(a*b);

break;

case '/':

push(a/b);

break;

default:

throw new RuntimeException("Invalid Operator!!");

return pop();

catch(Exception e)

[Link]("Error :"+[Link]());

return -1;

} //

package StackPkg; import

[Link]; public

class TestStack

public static void main(String[] args)

Scanner sc=new Scanner([Link]);


StackDemo sd=new StackDemo();

[Link]("Enter postfix expression(e.g.,23*5):");

String exp=[Link]();

int result = [Link](exp);

if(result!=-1)

[Link]("Result :"+result);

Output :-

16. Create a package HashSetPkg. Write a class Course with attributes courseId and courseName. Use
HashSet to store course objects and ensure no duplicate entries are allowed. Override equals() and
hashCode() methods. Write a main class to add and display unique courses. Code :- package
HashSetPkg;

import [Link]; public


class Course

int cid;

String cname;

public Course(int cid, String cname) {

super(); [Link]
= cid;
[Link] = cname;

@Override

public int hashCode() { return [Link](cid,


cname);

@Override

public boolean equals(Object obj)

if (this == obj)

return true;

if (!(obj instanceof Course))

return false;

Course c = (Course) obj;

return [Link] == [Link] && [Link]([Link]);

public void display()

[Link]("Course Id :"+cid+", Course Name :"+cname);

} //

package HashSetPkg;

import [Link].*; public

class TestCourse {

public static void main(String[] args)

{
Scanner sc=new Scanner([Link]);

HashSet<Course> set=new HashSet<Course>();

[Link]("Enter number of courses :");

int n=[Link]();

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

[Link]("Enter Course "+(i+1)+" details :");

[Link]("Course Id :");

int id=[Link]();

[Link]("Course Name :");

String name=[Link]();

Course c=new Course(id, name);

if([Link](c))

[Link]("course added..");

else

[Link]("Duplicate Course! not added..");

[Link]("\n--------Unique Course---------");

for(Course c:set)

{
[Link]();

Output :-

17. Create a package LinkedHashSetPkg. Write a class Book with attributes bookId and bookName.
Use LinkedHashSet to store book objects and maintain insertion order while avoiding duplicates.
Write a main class to demonstrate insertion and display order. Code :- package
LinkedHashSetPkg;

import [Link];

public class Book

int bookid;

String bookName;

public Book(int bookid, String bookName)

super(); [Link]
= bookid;

[Link] = bookName;
}

@Override

public int hashCode() {

return bookid+[Link]();

@Override

public boolean equals(Object obj)

if (this == obj)

return true;

if (!(obj instanceof Book))

return false;

Book other = (Book) obj;

return [Link] == [Link] && [Link]([Link]);

public void display()

[Link]("Book Id :"+bookid+", Book Name :"+bookName);

} //

package LinkedHashSetPkg; import

[Link]; import

[Link]; public class

TestBook {
public static void main(String[] args)

Scanner sc=new Scanner([Link]);

LinkedHashSet<Book> set=new LinkedHashSet<Book>();

[Link]("Enter [Link] Books :");

int n=[Link]();

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

[Link]("Enter Book Id :");

int id=[Link]();

[Link]("Enter Book Name :");

String name=[Link]();

Book b=new Book(id,name);

if([Link](b))

[Link]("Book Added..");

else

[Link]("Duplicate Book! Not added");

[Link]("----Book in insertion order----");


for(Book b:set)

{
[Link]();

Output :-

18. Create a package TreeSetPkg. Write a class Player with attributes id and score. Use TreeSet to
store player objects in sorted order based on score using Comparable. Write a main class to add
players and display sorted output. Code :- package TreeSetPkg; public class Player implements
Comparable<Player>

int id;

int score;

public Player(int id, int score)

super();

[Link] = id;

[Link] = score; }

@Override

public int compareTo(Player p)

{
return [Link];

public void display()

[Link]("ID :"+id+", Score :"+score);

} //

package TreeSetPkg; import

[Link]; import

[Link];

public class TestPlayer {

public static void main(String[] args)

Scanner sc=new Scanner([Link]);

TreeSet<Player> set=new TreeSet<Player>();

[Link]("Enter Number of players :");

int n=[Link]();

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

[Link]("\nEnter player " + (i + 1) + " details:");

[Link]("ID :"); int

id=[Link]();
[Link]("Score :");

int score=[Link]();

[Link](new Player(id, score));

[Link]("----Players sorted by score----");

for(Player p:set)

[Link]();

Output :-

19. Create a package TreeMapPkg. Write a class Library that uses TreeMap to store book ID and book
name as key-value pairs. Implement operations like add, remove, search, and display entries in
sorted order of keys. Write a main class to perform all operations using user input.

Code :-

package TreeMapPkg;

import [Link]; public

class Library

{
TreeMap<Integer,String> map=new TreeMap<Integer, String>();

public void addBook(int id,String name)

[Link](id, name);

[Link]("Book added..");

public void removeBook(int id)

if([Link](id))

[Link](id);

[Link]("Book removed..");

else

[Link]("Book not found..");

public void searchBook(int id)

if([Link](id))

[Link]("Book found :"+[Link](id));

else

[Link]("Book not found.");


}

public void displayBooks()

if([Link]())

[Link]("No Books available.");

else

[Link]("----Library Book (sorted by ID)----");

for(Integer id:[Link]())

[Link]("ID :"+id+", Name :"+[Link](id));

} //

package TreeMapPkg;

import [Link]; import


TreeMapPkg.*;

public class TestLibrary {

public static void main(String[] args)

Scanner sc=new Scanner([Link]); Library


lib=new Library();

int ch;
do

[Link]("1:Add Book");

[Link]("2:Remove Book");

[Link]("3:Search Book");

[Link]("4:Display Books");

[Link]("5:Exit");

[Link]("Enter Your Choice :");

ch=[Link]();

switch(ch)

case 1:

[Link]("Enter Book Id :");

int id=[Link]();

[Link]("Enter Book Name :");

String name=[Link]();

[Link](id, name);

break;

case 2:

[Link]("Enter Book Id to remove :");

[Link]([Link]());

break;

case 3:

[Link]("Enter Book ID to search :");

[Link]([Link]());

break;
case 4:

[Link]();

break;

case 5:

[Link]("Exit");

break;

default:

[Link]("Invalid choice");

}while(ch!=5);

Output :-

You might also like