1) Set First and Last
Description
Your task here is to implement a Java code based on the following
specifications. Note that your code should match the specifications in a
precise manner. Consider default visibility of class unless mentioned
otherwise.
class definitions:
Employee:
class Variables:
private String firstName
private String lastName
private String ssn
Constructor:
Employee():Empty constructor to intialise the instance variable as
null.A testcase will check for the creation of empty constructor.
visibility: public
Employee(firstName,lastName,ssn): arameterized constructor to
initialize the instance variables.
visibility: public
Getter Methods:
getFirstName(): Return the firstName.
Visibility: public
Return type: String
getLastName(): Return the lastName.
Visibility: public
Return type: String
getSsn(): Return the ssn.
Visibility: public
Return type: StringValidation Methods:
validateName(String firstName, String lastName): Implement this
function with three Exception- Explained below in Task section.
Use try-catch block to implement exception and return the
suitable Exception Messages from the catch block.
If the firstName and lastName is valid then assign the firstName,
lastName to appropriate Class variable and return "Valid String".
Visibility: public
Return type: String
validateSsn(String ssn): Check if the first and last character of the
ssn is digit return "Valid String" else return "Invalid String"
Visibility: public
Return-type: String
Your Task is to:
Implement the Employee class according to the above specification.
Employee class has three private variable : firstName, lastName,
ssn.
Employee Class contains three getter method. Implement the getter
methods first and then implement the validation methods. Strictly
follow the above specification order.
Validation Methods:
1. validateName(String firstName, String lastName): The three
exception to be checked are:
First if the firstName or lastName is null throw
NullPointerException("Entry Missing").
Second if the firstName or lastName length is zero throw
StringIndexOutOfBoundsException("Index out of bound").
Third if the firstName or lastName starts with a number throw
IllegalArgumentException("First Character is Invalid").
If the firstName and lastName is valid then assign the firstName,
lastName to appropriate Employee Class variable and return "Valid
String".
Use try block to check for the three exceptions and use catch block to
return the suitable exception message(For each exception, messages are
given in the specification eg. for StringIndexOutOfBoundsException
("Index out of bound") return message should be "Index out of
bound" ). Both this function has a String return type.
2. validateSsn (String ssn) : Check if the first and last character of the ssn
is digit(0-9) return "Valid String" else return "Invalid String".
Important:
To check your program you have to use the main() function (in Source
class) given in the stub. You can make suitable function calls and
use RUN CODE button to check your main() function output.
SOLUTION:
class Employee {
// Implement the class according to the specification
given in the stub..
private String firstName;
private String lastName;
private String ssn;
public Employee(){
}
public Employee(String firstName,String lastName,String
ssn){
[Link]=firstName;
[Link]=lastName;
[Link]=ssn;
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public String getSsn(){
return ssn;
}
public String validateName(String firstName,String
lastName){
try{
if(firstName==null||lastName==null){
throw new NullPointerException("Entry
Missing");
}
if([Link]()==0||[Link]()==0)
{
throw new
StringIndexOutOfBoundsException("Index out of bound");
}
if([Link]([Link](0))||
[Link]([Link](0))){
throw new IllegalArgumentException("First
Character is Invalid");
}
[Link]=firstName;
[Link]=lastName;
return "Valid String";
}catch(NullPointerException e){
return [Link]();
}catch(StringIndexOutOfBoundsException e){
return [Link]();
}catch(IllegalArgumentException e){
return [Link]();
}
}
public String validateSsn(String ssn){
if([Link]([Link](0))&&[Link]([Link]
t([Link]()-1))){
return "Valid String";
}
return "Invalid String";
}
public class Source{
public static void main(String[] args) {
//Implemnt main() to check your program...
//Don't remove the main() function or RUN CODE will not
work...
NOTE: HERE DON’T WRITE ANYTHING IN MAIN METHOD IN DO SELECT.
------------------------------------------------------------------------------------------------------------
------
2) Java :Portal for a Hotel
Description
Problem Statement
A portal is to be created for a hotel to manage room bookings for their
customers and provide information on room availability and bookings. The
system consists of several classes, each with its own set of properties and
methods:
1. Room
-> Represent a hotel room.
Properties:
roomNumber - Represents the room number.
roomType - Represents the room type (e.g., STANDARD, DELUXE,
SUITE).
roomStatus - Represents the room status (e.g., AVAILABLE, BOOKED).
bookingPrice - Represents the room booking price.
startDate - Represents the check-in date.
endDate - Represents the check-out date.
-> For instance variable roomNumber, return its value.
->Initialize the data members on object creation.
Method:
isRoomAvailable- Return true if the room is available for the specified
check-in and check-out dates; otherwise, return false.
2. RoomBooking
->Manages the bookings for a room.
Properties:
reservationNumber - Represents the reservation number.
startDate - Represents the check-in date.
endDate - Represents the check-out date.
durationinDays - Represents the stay duration.
status - Represents the booking status (e.g., CONFIRMED, CANCELLED,
PENDING).
advancePayment - Represents the advanced payment amount.
roomList - Represents the list of rooms booked as part of this booking.
dataLoader - Represents the class used to store rooms and room
booking data.
->Initialize dataLoader attribute on object creation.
Methods:
createRoomBooking - Create a booking for the given reservation
number and update the room status to BOOKED.
fetchRoomBookings - Fetch room booking details for the given
reservation number.
3. RoomSearch
->Responsible for searching available and booked rooms.
Properties:
dataLoader - Used to access room and room booking data.
->Initialize the data member on object creation.
Methods:
searchAvailableRooms - Search and return a list of available rooms
matching the specified room type and dates.
searchBookedRooms- Search and return a list of booked rooms
matching the specified room type and dates.
4. DataLoader
->Singleton class used to store rooms and room booking data in collections.
Properties:
roomsMap - Stores room numbers as keys and Room objects as
values.
roomBookingMap - Stores booking IDs as keys and RoomBooking
objects as values.
-> Initialize the data members on object creation and should only be visible
within the class, not from any other class (including subclasses).
Methods:
getInstance - Return an instance of the DataLoader class (as it's a
singleton class).
initialize - Populate roomsMap with the given list of rooms.
createRoomBookings- Update room status to BOOKED, create a
RoomBooking object and store it in roomBookingMap.
getRoomBookings - Return a RoomBooking from roomBookingMap
based on the given reservation number.
Enumerations:
BookingStatus - Values: CONFIRMED, CANCELLED, PENDING
RoomType - Values: STANDARD, DELUXE, SUITE
RoomStatus - Values: AVAILABLE, BOOKED
Sample Input:
Date checkInDate = new Date(2023, 1, 1);
Date checkOutDate = new Date(2023, 1, 2);
List<Room> rooms = new ArrayList<>();
[Link](new Room("F1", [Link], [Link],
checkInDate, checkOutDate));
[Link](new Room("F2", [Link], [Link],
checkInDate, checkOutDate));
[Link](new Room("F3", [Link], [Link],
checkInDate, checkOutDate));
DataLoader dataLoader = [Link]();
[Link](rooms);
RoomBooking roomBooking = new RoomBooking(dataLoader);
RoomBooking createdBooking = [Link]("RB1",
checkInDate, checkOutDate, rooms);
RoomSearch roomSearch = new RoomSearch(dataLoader);
List<Room> availableRooms =
[Link]([Link], checkInDate,
checkOutDate);
[Link](0).getRoomNumber();
[Link](1).getRoomNumber();
Sample Output:
F2
F3
------------------------------------------------------------------------------------------------------------
------
3) Employee Service Implementation
Description
Case Study:
Student Scholarship Scheme:
By default, all students in a college will be assigned with a Scholarship
scheme based on the score range of the student. Refer the below given
table to find the eligible scholarship scheme specific to a student.
score | Scholarship Scheme
score > 95 | Scheme a
score >= 90 and score <= 95 | Scheme b
score < 90 | no scheme
Task
On the basis of above case study implement a class to accept multiple
student details and store all student objects in a HashMap. The
functionalities need to be implemented are as follows:
1. Add student details to HashMap.
2. Accept scholarship scheme and display student details based on
scholarship scheme.
3. Delete student details from map.
Note: Refer the code stub for more clarity.
Sample Input
Student s= new Student("Alice", 10, 94);
70
11
Sample Output
Name: Alice Id: 10 Score: 94 ScholarshipScheme: scheme b
no scheme
false
IMPORTANT:
If you want to test your program you can implement a Main() method
given in the stub and you can use RUN CODE to test your Main(),
provided you have made valid function calls with valid data required.
SOLUTION:
import [Link];
import [Link].*;
class Students {
private String name;
private int id;
private int score;
private String scholarshipScheme;
public Students(String name, int id, int score) {
[Link] = name;
[Link] = id;
[Link] = score;
[Link] = assignScholarshipScheme(score);
}
private String assignScholarshipScheme(int score) {
if (score > 95) {
return "scheme a";
} else if (score >= 90 && score <= 95) {
return "scheme b";
} else {
return "no scheme";
}
}
public String getScholarshipScheme() {
return scholarshipScheme;
}
@Override
public String toString() {
return "Name: " + name + " Id: " + id + " Score: " +
score + " ScholarshipScheme: " + scholarshipScheme;
}
}
class StudentManager {
private Map<Integer, Students> studentMap;
public StudentManager() {
studentMap = new HashMap<>();
}
// 1. Add student details to HashMap
public void addStudent(Students student) {
[Link]([Link](), student);
}
// 2. Accept scholarship scheme and display student details
based on scholarship scheme
public void displayStudentsByScholarship(String
scholarshipScheme) {
boolean found = false;
for (Students student : [Link]()) {
if
([Link]().equalsIgnoreCase(scholarshipSche
me)) {
[Link](student);
found = true;
}
}
if (!found) {
[Link](scholarshipScheme);
}
}
// 3. Delete student details from map
public boolean deleteStudent(Students student) {
return [Link]([Link](), student);
}
}
public class Source {
public static void main(String[] args) {
StudentManager manager = new StudentManager();
// Sample Input
Students s = new Students("Alice", 10, 94);
[Link](s);
// Display "scheme b" student
[Link]("scheme b");
// Display "no scheme" student
[Link]("no scheme");
// Attempt to delete student with ID 11
Students dummy = new Students("Dummy", 11, 70);
[Link]([Link](dummy));
}
}
------------------------------------------------------------------------------------------------------------
------
4) Stone Processing
Description
You are working on a project to process stones in a stone quarry using Java.
Each stone has different characteristics, such as weight (in kilograms) and
color. Your task is to write a Java program that uses the Stream API to
perform various operations on a collection of stones. Note that your code
should match the specifications in a precise manner. Consider default
visibility of classes, data fields, and methods unless mentioned otherwise.
Specifications:
class definitions:
class Stone:
data member:
double weight
String color
visibility: private
Stone(double weight, String color) : Define the constructor with public
visibility
Define getters for all the data members with public visibility.
toString method has been defined for you as a part of the code stub.
class StoneProcessingApp:
method definitions:
getTotalWeight(List<Stone> stones):
return type: double
visibility: public
getRedStone(List<Stone> stones):
return type: List<Stone>
visibility: public
getHeaviestStone(List<Stone> stones):
return type: Stone
visibility: public
Task:
class Stone:
- Define the class according to the above specifications
class StoneProcessingApp:
Implement the below method for this class using Stream API methods:
double getTotalWeight(List<Stone> stones): Calculate and return
the total weight of all stones.
List<Stone> getRedStone(List<Stone> stones): Find and return
all stones that are of a specific color ("red").
Stone getHeaviestStone(List<Stone> stones): Find and return
the heaviest stone in terms of weight.
Sample Input
List<Stone> stones = new ArrayList<>();
[Link](new Stone(5.0, "red"));
[Link](new Stone(8.0, "blue"));
[Link](new Stone(6.5, "red"));
[Link](new Stone(4.2, "green"));
[Link](new Stone(7.8, "blue"));
StoneProcessingApp sta = new StoneProcessingApp();
[Link](stones);
[Link](stones);
[Link](stones);
Sample Output
31.5
[Stone{weight=5.0, color='red'}, Stone{weight=6.5, color='red'}]
Stone{weight=8.0, color='blue'}
Note:
import [Link].*;
class Stone {
private double weight;
private String color;
// Constructor with public visibility
public Stone(double weight, String color) {
[Link] = weight;
[Link] = color;
}
// Getters for weight and color
public double getWeight() {
return weight;
}
public String getColor() {
return color;
}
@Override
public String toString() {
return "Stone{" +
"weight=" + weight +
", color='" + color + '\'' +
'}';
}
}
class StoneProcessingApp {
// Method to calculate the total weight of all stones
public double getTotalWeight(List<Stone> stones) {
return [Link]()
.mapToDouble(Stone::getWeight)
.sum();
}
// Method to find all stones that are red
public List<Stone> getRedStone(List<Stone> stones) {
return [Link]()
.filter(stone ->
"red".equalsIgnoreCase([Link]()))
.collect([Link]());
}
// Method to find the heaviest stone
public Stone getHeaviestStone(List<Stone> stones) {
return [Link]()
.max([Link](Stone::getWeight
))
.orElse(null); // In case there are no stones
}
}
public class Source {
public static void main(String[] args) {
// Create a list of stones
List<Stone> stones = new ArrayList<>();
[Link](new Stone(5.0, "red"));
[Link](new Stone(8.0, "blue"));
[Link](new Stone(6.5, "red"));
[Link](new Stone(4.2, "green"));
[Link](new Stone(7.8, "blue"));
// Create an instance of StoneProcessingApp
StoneProcessingApp sta = new StoneProcessingApp();
// Get total weight of all stones
double totalWeight = [Link](stones);
[Link](totalWeight); // Expected output:
31.5
// Get all stones that are red
List<Stone> redStones = [Link](stones);
[Link](redStones); // Expected output:
[Stone{weight=5.0, color='red'}, Stone{weight=6.5, color='red'}]
// Get the heaviest stone
Stone heaviestStone = [Link](stones);
[Link](heaviestStone); // Expected output:
Stone{weight=8.0, color='blue'}
}
}
------------------------------------------------------------------------------------------------------------
------
5) Parcel Management System
Description
Problem Statement
You are tasked with implementing a simple Parcel Delivery System in Java.
The system should be able to handle parcels, each identified by a unique
parcel ID. Each parcel has sender and recipient names, an address, weight,
and delivery status.
Address Class:
->Create a class named Address with attributes for street, city, state, and zip
code, making them only accessible within the declared class.
->Initialize the data members for the object of the class.
->Override the toString method to return a formatted string representation
of the address.(Follow the below format)
street + ", " + city + ", " + state + ", " + zipCode
Parcel Class:
->Create a class named Parcel with the following private attributes:
parcelId (a unique identifier for each parcel, starting from 1 and
incrementing with each new parcel)
senderName
recipientName
address (an instance of the Address class)
weight
deliveryStatus
->Initialize the data members for the object of the class.
->Implement methods:
getParcelId() to retrieve the parcel ID.
setParcelId(int parcelId) to set a specific parcel ID.
updateStatus(String newStatus) to update the delivery status of
the parcel.
Override the toString method to return a formatted string
representation of the parcel, including all its details.(Follow the below
format)
"Parcel{" +
"parcelId=" + parcelId +
", senderName='" + senderName + '\'' +
", recipientName='" + recipientName + '\'' +
", address=" + address +
", weight=" + weight +
", deliveryStatus='" + deliveryStatus + '\'' +
'}'
ParcelDeliverySystem Class:
->Create a class named ParcelDeliverySystem to manage a list of parcels.
->Initialize the data members for the object of the class.
->Implement methods:
addParcel(Parcel parcel) to add a new parcel to the system.
updateParcelStatus(int parcelId, String newStatus) to update
the delivery status of a specific parcel.
viewParcelDetails(int parcelId) to retrieve and display the details of
a specific parcel.
Implementation Requirements:
The system should ensure that each parcel has a unique identifier.
The system should handle the addition of parcels, updating their
delivery status, and viewing parcel details.
The classes should have appropriate encapsulation and error handling
(e.g., checking if a parcel with a given ID exists before updating its
status).
Demonstrate the functionality of the system by creating instances of
parcels, adding them to the system, updating their status, and viewing
their details.
Sample Input
ParcelDeliverySystem deliverySystem = new ParcelDeliverySystem();
Address senderAddress = new Address("123 Main St", "Cityville", "State",
"12345");
Address recipientAddress = new Address("456 Oak St", "Townsville", "State",
"67890");
Parcel parcel1 = new Parcel("Sender1", "Recipient1", senderAddress, 2.5, "In
Transit");
Parcel parcel2 = new Parcel("Sender2", "Recipient2", recipientAddress, 1.8,
"Pending");
[Link](parcel1);
[Link](1);
[Link](2, "Delivered");
Sample Output
Parcel added successfully.
Parcel Details:Parcel{parcelId=1, senderName='Sender1',
recipientName='Recipient1', address=123 Main St, Cityville, State, 12345,
weight=2.5, deliveryStatus='In Transit'}
Parcel not found with ID 2
//Address Class
class Address {
private String street;
private String city;
private String state;
private String zipCode;
public Address(String street, String city, String state, String
zipCode) {
[Link] = street;
[Link] = city;
[Link] = state;
[Link] = zipCode;
}
@Override
public String toString() {
return street + ", " + city + ", " + state + ", " +
zipCode;
}
}
//Parcel Class
class Parcel {
private static int idCounter = 1;
private int parcelId;
private String senderName;
private String recipientName;
private Address address;
private double weight;
private String deliveryStatus;
public Parcel(String senderName, String recipientName, Address
address, double weight, String deliveryStatus) {
[Link] = idCounter++;
[Link] = senderName;
[Link] = recipientName;
[Link] = address;
[Link] = weight;
[Link] = deliveryStatus;
}
public int getParcelId() {
return parcelId;
}
public void setParcelId(int parcelId) {
[Link] = parcelId;
}
public void updateStatus(String newStatus) {
[Link] = newStatus;
}
@Override
public String toString() {
return "Parcel{" +
"parcelId=" + parcelId +
", senderName='" + senderName + '\'' +
", recipientName='" + recipientName + '\'' +
", address=" + address +
", weight=" + weight +
", deliveryStatus='" + deliveryStatus + '\'' +
'}';
}
}
//ParcelDeliverySystem Class
//ParcelDeliverySystem Class
class ParcelDeliverySystem {
private Map<Integer, Parcel> parcels;
public ParcelDeliverySystem() {
parcels = new HashMap<>();
}
// Returns a success message after adding a parcel
public String addParcel(Parcel parcel) {
[Link]([Link](), parcel);
return "Parcel added successfully.";
}
// Returns a message indicating success or failure of status
update
public String updateParcelStatus(int parcelId, String
newStatus) {
Parcel parcel = [Link](parcelId);
if (parcel != null) {
[Link](newStatus);
return "Parcel status updated successfully.";
} else {
return "Parcel not found with ID " + parcelId;
}
}
// Returns the parcel details as a string
public String viewParcelDetails(int parcelId) {
Parcel parcel = [Link](parcelId);
if (parcel != null) {
return "Parcel Details:" + parcel; // Make sure there is no
extra space
} else {
return "Parcel not found with ID " + parcelId;
}
}
public class Source {
public static void main(String args[]) {
// Create instances of Address
Address senderAddress = new Address("123 Main St",
"Cityville", "State", "12345");
Address recipientAddress = new Address("456 Oak St",
"Townsville", "State", "67890");
// Create instances of Parcel
Parcel parcel1 = new Parcel("Sender1", "Recipient1",
senderAddress, 2.5, "In Transit");
Parcel parcel2 = new Parcel("Sender2", "Recipient2",
recipientAddress, 1.8, "Pending");
// Create ParcelDeliverySystem instance
ParcelDeliverySystem deliverySystem = new
ParcelDeliverySystem();
// Add parcels to the system
[Link](parcel1);
[Link](parcel2);
// View parcel details
[Link](1);
// Update parcel status
[Link](2, "Delivered");
// Try to view a non-existing parcel
[Link](2); // Parcel not found
}
}
------------------------------------------------------------------------------------------------------------
------
6) Color Palette
Description
Problem Statement
You are tasked with creating a custom palette generator in Java using
EnumSet to manage colors in a color palette. The palette should be used to
create various color schemes based on user preferences.
Here's what the problem entails:
Color Enum:
->Define an enum named Colour that includes a variety of colors. Each
color should have a name and an associated RGB value.
-> The enum defines various color constants along with their
corresponding [Link] values.
->The private final Color color field is set for each constant.
-> The constructor initializes each color constant with its associated color.
->The getColor() method should retrieve the corresponding [Link]
object.
ColorPalette Class:
-> Create a class named ColorPalette that utilizes EnumSet to store a
collection of colors.
->This class should include methods to:
->void addColor(Colour color):
This method allows you to add a color of the Colour enum to the
palette.
It takes a Colour enum value as a parameter and adds it to the palette
EnumSet.
->EnumSet<Colour> generateTriadicScheme(Colour baseColor):
This method generates a triadic color scheme based on a given base
color.
Triadic color schemes are composed of three colors evenly spaced
around the color wheel.
It calculates the two triadic colors using the findTriadicColors private
method.
Returns an EnumSet containing the base color and its two triadic
colors.
->EnumSet<Colour> generateAnalogousScheme(Colour baseColor):
This method generates an analogous color scheme based on a given
base color.
Analogous color schemes are composed of colors that are adjacent on
the color wheel.
It calculates the two analogous colors using the findAnalogousColors
private method.
Returns an EnumSet containing the base color and its two analogous
colors.
->private Colour[] findTriadicColors(Colour baseColor):
This is a private helper method used to calculate the two triadic colors
for a given base color.
It takes the base color, calculates its index within the enum, and finds
the two colors that are two and four positions away in the enum array.
Returns an array of Colour containing the two triadic colors.
->private Colour[] findAnalogousColors(Colour baseColor):
This is a private helper method used to calculate the two analogous
colors for a given base color.
Similar to the triadic case, it calculates the index of the base color and
finds the colors that are one and five positions away in the enum array.
Returns an array of Colour containing the two analogous colors.
Remember that you can leverage the [Link] class to represent
colors using RGB values and perform color calculations.
Sample Input
ColorPalette palette = new ColorPalette();
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
Colour baseColor = [Link];
[Link](baseColor);
[Link](baseColor);
Sample Output
[RED, BLUE, ORANGE]
[RED, GREEN, PURPLE]
//Enum representing different colors with associated RGB values
enum Colour {
RED([Link]),
GREEN([Link]),
BLUE([Link]),
YELLOW([Link]),
ORANGE([Link]),
PURPLE(new Color(128, 0, 128)),
CYAN([Link]),
MAGENTA([Link]);
private final Color color;
// Constructor to initialize the color with a corresponding RGB
value
Colour(Color color) {
[Link] = color;
}
// Getter method to retrieve the Color object
public Color getColor() {
return color;
}
}
//Class representing the color palette
class ColorPalette {
private EnumSet<Colour> palette;
// Constructor initializes the palette as an empty EnumSet
public ColorPalette() {
palette = [Link]([Link]);
}
// Method to add a color to the palette
public void addColor(Colour color) {
[Link](color);
}
// Method to generate a triadic color scheme based on a base
color
public EnumSet<Colour> generateTriadicScheme(Colour baseColor)
{
EnumSet<Colour> triadicScheme = [Link](baseColor);
Colour[] triadicColors = findTriadicColors(baseColor);
[Link](triadicColors[0]);
[Link](triadicColors[1]);
return triadicScheme;
}
// Method to generate an analogous color scheme based on a base
color
public EnumSet<Colour> generateAnalogousScheme(Colour
baseColor) {
EnumSet<Colour> analogousScheme = [Link](baseColor);
Colour[] analogousColors = findAnalogousColors(baseColor);
[Link](analogousColors[0]);
[Link](analogousColors[1]);
return analogousScheme;
}
// Private method to find triadic colors for a given base color
private Colour[] findTriadicColors(Colour baseColor) {
Colour[] allColors = [Link]();
int baseIndex = [Link]();
// Calculate triadic colors by finding colors 2 and 4 steps
away in the enum
Colour firstTriadic = allColors[(baseIndex + 2) %
[Link]];
Colour secondTriadic = allColors[(baseIndex + 4) %
[Link]];
return new Colour[]{firstTriadic, secondTriadic};
}
// Private method to find analogous colors for a given base
color
private Colour[] findAnalogousColors(Colour baseColor) {
Colour[] allColors = [Link]();
int baseIndex = [Link]();
// Calculate analogous colors by finding colors 1 and 5
steps away in the enum
Colour firstAnalogous = allColors[(baseIndex + 1) %
[Link]];
Colour secondAnalogous = allColors[(baseIndex + 5) %
[Link]];
return new Colour[]{firstAnalogous, secondAnalogous};
}
}
//Main class to demonstrate the functionality
public class Source {
public static void main(String[] args) {
// Create a ColorPalette instance
ColorPalette palette = new ColorPalette();
// Add colors to the palette
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
// Choose a base color for the schemes
Colour baseColor = [Link];
// Generate and display the Triadic color scheme
[Link]([Link](baseColor));
// Generate and display the Analogous color scheme
[Link]([Link](baseColor));
}
}
------------------------------------------------------------------------------------------------------------
------
7) Seasonal Activities Organizer
Description
Problem Statement
You are building an application that helps users organize their seasonal
activities based on the weather conditions. You want to use EnumSet to
efficiently manage the activities for each season.
-> Create a Season enum that includes various types of
seasons SPRING, SUMMER, AUTUMN (Fall), and WINTER.
->Create an Activity enum that includes various types of activities
like HIKING, SWIMMING, SKIING, PUMPKIN_CARVING
class SeasonalActivityOrganizer
->Your task is to implement the following:
->Create an EnumSet for each season to store the activities that are
appropriate for that season.
->getActivitiesForSeason(Season season):
This method takes a Season enum value as input and returns a set of
Activity enum values that are suitable for the given season.
The default case in the switch statement should include appropriate error
handling for cases where an unknown or unsupported season value is
provided.
("Unknown season: " + season)
->addActivityForSeason(Activity activity, Season season):
This method adds an Activity enum value to the set of activities
appropriate for the specified season and then returns the updated set
of activities for that season("Unknown season: " + season).
The default case in the switch statement should include appropriate error
handling for cases where an unknown or unsupported season value is
provided("Unknown season: " + season).
->removeActivityFromAllSeasons(Activity activity):
This method removes an Activity enum value from the set of activities
for all seasons if it exists and then returns the updated set of all
activities.
->getAllActivities():
This method returns a set containing all the Activity enum values from
all seasons.
Sample Input
SeasonalActivityOrganizer organizer = new SeasonalActivityOrganizer();
[Link]([Link], [Link]);
[Link]([Link], [Link]);
[Link]([Link], [Link]);
[Link]()
[Link]([Link])
[Link]([Link])
[Link]([Link])
[Link]([Link]);
[Link]([Link])
Sample Output
[HIKING, SWIMMING, SKIING]
[HIKING]
[SWIMMING]
[SKIING]
[]
enum Season{
SPRING, SUMMER, AUTUMN,WINTER
}
enum Activity{
HIKING, SWIMMING, SKIING, PUMPKIN_CARVING
}
class SeasonalActivityOrganizer {
private final EnumSet<Activity> SpringActivities =
[Link]([Link]);
private final EnumSet<Activity> SummerActivities =
[Link]([Link]);
private final EnumSet<Activity> AutumnActivities =
[Link]([Link]);
private final EnumSet<Activity> winterActivities =
[Link]([Link]);
public Set<Activity> getActivitiesForSeason(Season season){
switch(season){
case SPRING:
return SpringActivities;
case SUMMER:
return SummerActivities;
case AUTUMN:
return AutumnActivities;
case WINTER:
return winterActivities;
default:
throw new IllegalArgumentException("unknown Season:
"+season);
}
}
public Set<Activity> addActivityForSeason(Activity activity,
Season season){
switch(season){
case SPRING:
[Link](activity);
return SpringActivities;
case SUMMER:
[Link](activity);
return SummerActivities;
case AUTUMN:
[Link](activity);
return AutumnActivities;
case WINTER:
[Link](activity);
return winterActivities;
default:
throw new IllegalArgumentException("Unknown Season:
"+season);
}
}
public Set<Activity> removeActivityFromAllSeasons(Activity
activity){
[Link](activity);
[Link](activity);
[Link](activity);
[Link](activity);
return getAllActivities();
}
public Set<Activity>getAllActivities(){
EnumSet<Activity> allActivities =
[Link]([Link]);
[Link](SpringActivities);
[Link](SummerActivities);
[Link](AutumnActivities);
[Link](winterActivities);
return allActivities;
}
}
public class Source{
public static void main(String args[] ) throws Exception {
SeasonalActivityOrganizer organizer = new
SeasonalActivityOrganizer();
[Link]([Link],
[Link]);
[Link]([Link],
[Link]);
[Link]([Link],
[Link]);
[Link]([Link]());
[Link]([Link]([Link]
G));
[Link]([Link]([Link]
R));
[Link]([Link]([Link]
R));
[Link]([Link]);
[Link]([Link]([Link]
G));
}}
8. DRUG MANAGEMENT
Problem Statement
You are tasked with developing a program to manage drugs and store
information for a retail drug pharmacy. This problern requires you to
implement three classes: Item, Drug, and Store.
Class Item:
->This class represents an item.
Attributes:
• itemNumber: Store the item number.
• item Name: Store the name of the item.
• price: Store the price of the item.
Methods:
⚫ getitemNumber(): Return the item number.
⚫ getItemName(): Return the name of the item.
• getPrice(): Return the price of the item.
Class Drug:
->This class contains the following attributes and methods:
Attributes:
• drugClass: Store the drug class name.
• expiration Date: Store the expiration date of the drug.
Methods:
• getDrug Class(): Return the drug class.
• getlsExpired(): Return true if the item expires before today's date;
otherwise, returns false.
Class Store,
->This class represents a drug retail store.
Attributes:
• storeNumber. Store the number of the store.
• city: Store the city of the store.
map: Store a mapping of drug classes to lists of drugs.
Methods:
• addDrug(Drug drug): Add the given drug to the store. The drugs should be
organized by their drug classes.
• getDrugs (String drugClass): Return a list of drugs for the given drug class.
Sample Input
Drug drug1 = new Drug("D1", "ibuprofen", 2.5);
[Link]("2022-10-01");
[Link]("OTC");
[Link]();
Drug drug2 = new Drug("52", "pentocid", 2.5);
[Link]("2025-11-02");
[Link]("OTC");
[Link]();
Store londonStore = new Store("londonstore", "London");
[Link](drug1);
[Link](drug2);
List<Drug> drugs = [Link] ("OTC");
Sample Output
true
false
[Item{itemNumber='D1', itemName='ibuprofen', price-2.5},
Item{itemNumber='D2', itemName='pentocid', price=2.5}]
Note:
You can make suitable function calls and use the RUN CODE button to check
your main() method output.
import [Link].*;
//Your-Code Goes Here..
public class Source-{
public static void main(String args[]) throws Exception {
/*-Enter-your-code-here. Read-input-from-STDIN. Print-output-to- }
SOLUTION:
import [Link];
import [Link].*;
class Item {
private String itemNumber;
private String itemName;
private double price;
public Item(String itemNumber, String itemName, double price) {
[Link] = itemNumber;
[Link] = itemName;
[Link] = price;
}
public String getItemNumber() {
return itemNumber;
}
public String getItemName() {
return itemName;
}
public double getPrice() {
return price;
}
@Override
public String toString() {
return "Item{itemNumber='" + itemNumber + "', itemName='" + itemName + "', price=" + price + "}";
}
}
class Drug extends Item {
private String drugClass;
private String expirationDate;
public Drug(String itemNumber, String itemName, double price) {
super(itemNumber, itemName, price);
}
public void setDrugClass(String drugClass) {
[Link] = drugClass;
}
public String getDrugClass() {
return drugClass;
}
public void setExpirationDate(String expirationDate) {
[Link] = expirationDate;
}
public boolean isExpired() {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = [Link](expirationDate);
Date currentDate = new Date();
return [Link](currentDate);
} catch (Exception e) {
return false;
}
}
}
class Store {
private String storeNumber;
private String city;
private Map<String, List<Drug>> drugMap;
public Store(String storeNumber, String city) {
[Link] = storeNumber;
[Link] = city;
[Link] = new HashMap<>();
}
public void addDrug(Drug drug) {
String drugClass = [Link]();
[Link](drugClass, new ArrayList<>());
[Link](drugClass).add(drug);
}
public List<Drug> getDrugs(String drugClass) {
return [Link](drugClass, new ArrayList<>());
}
}
public class Source {
public static void main(String args[]) throws Exception {
Drug drug1 = new Drug("D1", "ibuprofen", 2.5);
[Link]("2022-10-01");
[Link]("OTC");
[Link]([Link]());
Drug drug2 = new Drug("D2", "pentocid", 2.5);
[Link]("2025-11-02");
[Link]("OTC");
[Link]([Link]());
Store londonStore = new Store("londonstore", "London");
[Link](drug1);
[Link](drug2);
List<Drug> drugs = [Link]("OTC");
[Link](drugs);
}
}
9. Parking Lot Simulation
subject Coding
casino 10 points
DESCRIPTION
Problem Statement
You are tasked with designing a simple parking lot management system. The
system should consist of two classes: Vehicle and ParkingLot.
Vehicle Class:
->Define the below attributes making them only accessible within the
declared class.
licensePlate: Represents the license plate of the vehicle.
vehicleType: Represents the type of the vehicle.
The Vehicle class has a constructor that takes in a licensePlate
and a vehicleType to initialize the attributes.
->The class provides two getter methods:
getLicensePlate(): Returns the license plate of the vehicle.
getVehicleType(): Returns the type of the vehicle.
ParkingLot Class:
->The ParkingLot class has the following private attributes:
maxCapacity: Represents the maximum capacity of the parking
lot.
currentOccupancy: Represents the current number of vehicles
parked in the lot.
parkedVehicles: Represents a list of vehicles currently parked in
the lot.
->The ParkingLot class has a constructor that takes in maxCapacity to
initialize the attributes. It also initializes an empty ArrayList for parked
vehicles.
->The class provides the following methods:
parkVehicle: Parks a vehicle in the parking lot. If there is space
available, the vehicle is added to the list, and the current
occupancy is updated. Return a message "Vehicle parked
successfully. Parking spot: " + currentOccupancy +
"." , indicating the vehicle was parked successfully, else, return a
message "Parking lot is full. Cannot park the vehicle. " if
the parking lot is full.
retrieveVehicle: Retrieve a vehicle from the parking lot based
on its license plate. If the vehicle is found, remove it from the list,
update the current occupancy, and return a message "Vehicle
with license plate " + licensePlate + " retrieved from
parking spot: " + (i + 1) + "." , indicating the retrieval. If the
vehicle is not found, return a message "Vehicle with license
plate " + licensePlate + " not found in the parking lot.",
stating that the vehicle is not in the parking lot.
getParkingLotStatus: Return a message "Current occupancy:
" + currentOccupancy + " vehicles" + "," +"Available
spaces: " + (maxCapacity - currentOccupancy) indicating
the current occupancy and available spaces in the parking lot.
Refer to the sample input output for clarity.
Note:
The parking lot should not allow more vehicles to be parked than
its maximum capacity.
When retrieving a vehicle, assume that there are no duplicate
license plates in the parking lot.
The parking spots are numbered starting from 1.
The getParkingLotStatus method should provide information
about the current occupancy and available spaces in the parking
lot.
Sample Input
[Link](new Vehicle("ABC123", "Car"));
[Link]("XYZ789");
[Link]();
Sample Output
Vehicle parked successfully. Parking spot: 1.
Vehicle with license plate XYZ789 not found in the parking lot.
Current occupancy: 1 vehicles,Available spaces: 4
NOTE:
You can make suitable function calls and use the RUN
CODE button to check your main() method output.
SOLUTION:
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
class Vehicle {
private String licensePlate;
private String vehicleType;
public Vehicle(String licensePlate, String vehicleType) {
[Link] = licensePlate;
[Link] = vehicleType;
}
public String getLicensePlate() {
return licensePlate;
}
public String getVehicleType() {
return vehicleType;
}
}
class ParkingLot {
private int maxCapacity;
private int currentOccupancy;
private ArrayList<Vehicle> parkedVehicles;
public ParkingLot(int maxCapacity) {
[Link] = maxCapacity;
[Link] = 0;
[Link] = new ArrayList<>();
}
public String parkVehicle(Vehicle vehicle) {
if (currentOccupancy < maxCapacity) {
[Link](vehicle);
currentOccupancy++;
return "Vehicle parked successfully. Parking spot: "
+ currentOccupancy + ".";
} else {
return "Parking lot is full. Cannot park the
vehicle.";
}
}
public String retrieveVehicle(String licensePlate) {
for (int i = 0; i < [Link](); i++) {
if
([Link](i).getLicensePlate().equals(licensePlate)) {
[Link](i);
currentOccupancy--;
return "Vehicle with license plate " +
licensePlate + " retrieved from parking spot: " + (i + 1) + ".";
}
}
return "Vehicle with license plate " + licensePlate + "
not found in the parking lot.";
}
public String getParkingLotStatus() {
return "Current occupancy: " + currentOccupancy + "
vehicles" + "," + "Available spaces: " + (maxCapacity -
currentOccupancy);
}
}
public class Source {
public static void main(String args[] ) throws Exception {
ParkingLot parkingLot = new ParkingLot(5);
[Link]([Link](new
Vehicle("ABC123", "Car")));
[Link]([Link]("XYZ789"));
[Link]([Link]());
}
}
10. Mobile Shop
subject Coding
casino 10 points
DESCRIPTION
Your task here is to implement Java code based on the following
specifications. Note that your code should match the specifications in a
precise manner. Consider default visibility of classes, data fields, and
methods unless mentioned.
Specifications
class definitions:
class Mobile:
data member:
HashMap<String, ArrayList<String>> mobileList = new
Hashmap<>()
method definition:
addMobile(String company, String model)
return type: String
visibility: public
getModels(String company)
return type: ArrayList<String>
visibility: public
buyMobile(String company, String model)
return type: String
visibility: public
Task
Class Mobile
-define the object of HashMap<String, ArrayList<String>> with
variable name mobileList.
The String defines the name of the company and
the Arraylist will have list of models.
Implement the below methods for this class:
-String addMobile(String company, String model):
Write a code to add a company with its model.
If the company does not exists then create it with a new String
list and add the model.
Update the String list with the new model if the company already
exists
return "model successfully added" after performing the above
operations
-ArrayList<String> getModel(String company):
Write a code to get the Model list.
return null if the given company doesn't exist or doesn't have any
model, else return the String list of all the models.
-String buyMobile(String company, String model):
Write a code to buy a mobile.
Remove the mobile model from the list according to the model
purchased. In case there are two same models then remove one
and return the message "mobile sold successfully
Return a message "item not available" if the mobile or model is
not present in the list
Sample Input
Mobile obj = new Mobile();
[Link]("Oppo", "K3");
[Link]("Oppo");
[Link]("Oppo", "K3");
Sample Output
model successfully added
[K3]
mobile sold successfully
NOTE:
You can make suitable function calls and use RUN CODE button
to check your main() method output.
SOLUTION:
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
class Mobile {
HashMap<String, ArrayList<String>> mobileList = new
HashMap<>();
public String addMobile(String company, String model)
{
if () {
[Link](company, new ArrayList<>());
}
[Link](company).add(model);
return "model successfully added";
}
public ArrayList<String> getModels(String company) {
if ([Link](company)) {
return [Link](company);
} else {
return null;
}
}
public String buyMobile(String company, String model)
{
if ([Link](company)) {
ArrayList<String> models =
[Link](company);
if ([Link](model)) {
[Link](model);
return "mobile sold successfully";
} else {
return "item not available";
}
}
return "item not available";
}
}
public class Source {
public static void main(String[] args) {
Mobile obj = new Mobile();
[Link]([Link]("Oppo", "K3"));
[Link]([Link]("Oppo"));
[Link]([Link]("Oppo", "K3"));
[Link]([Link]("Oppo", "K3"));
}
}
11. RED YELLOW GREEN
subject Coding
casino 10 points
DESCRIPTION
Complete the classes using the Specifications given below. Consider default
visibility of classes, data fields, and methods unless mentioned otherwise.
Specifications
enum definition:
enum TrafficColor:
RED("RED"),
YELLOW("YELLOW"),
GREEN("GREEN");
data member:
final String color
TrafficColor(String color)
method definition:
getColor():
return type:String
visibility: public
class TrafficLight:
method definitions:
static nextColor(TrafficColor currentColor):
return type: String
visibility: public
static printColor(TrafficColor currentColor):
return type: String
visibility: public
Task
enum TrafficColor
- Define an enum type called TrafficColor With three constants
representing the colors of a traffic light: RED, YELLOW, and GREEN.
-The TrafficColor enum has a constructor that takes the color name as an
argument and a getColor() method that returns the associated color name.
Class TrafficLight
-Implement the below methods for this class:
->static String nextColor(TrafficColor currentColor): take the current
color as an argument and return the next color in the sequence (RED ->
GREEN -> YELLOW -> RED).
->static String printColor(TrafficColor currentColor): return the string
representation of the input TrafficColor.
Sample Input1
TrafficColor currentColor = [Link];
[Link](currentColor)
Sample Output1
GREEN
NOTE:
You can make suitable function calls and use the RUN
CODE button to check your main() method output.
SOLUTION:
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
//Define enum here..
// Enum definition for TrafficColor
enum TrafficColor {
RED("RED"), YELLOW("YELLOW"), GREEN("GREEN");
// Data member for the color
private final String color;
// Constructor to set the color
TrafficColor(String color) {
[Link] = color;
}
// Method to get the color name
public String getColor() {
return [Link];
}
}
// Class definition for TrafficLight
class TrafficLight {
// Method to get the next color in the sequence
public static String nextColor(TrafficColor currentColor) {
switch (currentColor) {
case RED:
return [Link]();
case GREEN:
return [Link]();
case YELLOW:
return [Link]();
default:
return null;
}
}
// Method to print the color of the current TrafficColor
public static String printColor(TrafficColor currentColor)
{
return [Link]();
}
}
// Main class to test the methods
public class Source {
public static void main(String args[]) throws Exception {
// Example test case
TrafficColor currentColor = [Link];
// Test nextColor method
[Link]([Link](currentColor));
// Expected output: GREEN
// Test printColor method
[Link]([Link](currentColor));
// Expected output: RED
}
}
12. Spring Has Come
subject Coding
casino 10 points
DESCRIPTION
Complete the classes using the Specifications given below. Consider default
visibility of classes, data fields, and methods unless mentioned otherwise.
Specifications
class Definition:
class SeasonExample:
enum definition:
enum Season
SPRING,
SUMMER,
FALL,
WINTER
visibility: public
method definitions:
static getSeason(int month):
return type: String
visibility: public
static printSeason(Season season):
return type: String
visibility: public
Task
Class SeasonExample
-Define enum Season according to the above specifications
-Implement the below methods for this class:
->static String getSeason(int month):
Take an integer parameter representing the month (1-12) and
return the corresponding season based on the traditional division
of the year into four seasons:
Spring: March (3) to May (5)
Summer: June (6) to August (8)
Fall: September (9) to November (11)
Winter: December (12), January (1), and February (2)
->static String printSeason(Season season):
Take Season parameter and display the month in a string as
given:
SPRING: "SPRING Season"
SUMMER: "SUMMER Season"
FALL: "FALL Season"
WINTER: "WINTER Season"
Sample Input
SeasonExample se = new SeasonExample();
String season = [Link](7);
[Link]([Link](season));
Sample Output
SUMMER Season
NOTE:
You can make suitable function calls and use the RUN
CODE button to check your main() method output.
SOLUTION:
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
class SeasonExample {
//Code Here..
public enum Season {
SPRING,
SUMMER,
FALL,
WINTER
}
public static String getSeason(int month) {
if (month >= 3 && month <= 5) {
return "SPRING";
} else if (month >= 6 && month <= 8) {
return "SUMMER";
} else if (month >= 9 && month <= 11) {
return "FALL";
} else {
return "WINTER";
}
}
public static String printSeason(Season season) {
switch (season) {
case SPRING:
return "SPRING Season";
case SUMMER:
return "SUMMER Season";
case FALL:
return "FALL Season";
case WINTER:
return "WINTER Season";
default:
return "Unknown Season";
}
}
}
public class Source {
public static void main(String args[] ) throws Exception {
/* Enter your code here. Read input from STDIN. Print
output to STDOUT */
SeasonExample se = new SeasonExample();
String season = [Link](7);
[Link]([Link]([Link](s
eason)));
}
}
13. School Management
subject Coding
casino 10 points
DESCRIPTION
Problem Statement:
You are tasked with designing a program for managing class and student
information in a school. The program should include three classes: Person,
Student, and AcademicClass.
Class Person
Attributes:
Name: Store the name of the person.
Age: Store the age of the person.
Gender: Store the gender of the person.
Address: Store the address of the person.
Methods:
getName(): Return the name of the person.
getAge(): Return the age of the person.
getGender(): Return the gender of the person.
getAddress(): Return the address of the person.
Class Student:
-> Inherit attributes and methods from Person class
Attributes:
Map<String, Integer> map: Store marks for each subject.
Methods:
addMarks(String subject, int marks): Add marks for a given
subject.
getMarks(String subject): Return marks for a given subject.
getTotalMarks(): Return the total marks for all subjects.
Class AcademicClass:
Attributes:
className: Store the name of the class.
students: Stores a collection of students.
Methods:
getClassName(): Return the name of the class.
addStudent(Student student): Add a given student to the
collection.
addStudents(List<Student> students): Add a given
collection of students.
getTopper(): Return information about the student with the
highest marks.
Sample Input
Student raj = new Student("Raj", 11, 'M', "Noida");
[Link]("Hindi", 90);
[Link]("English", 95);
[Link]("Mathematics", 100);
Student sumit = new Student("Sumit", 10, 'M', "Delhi");
[Link]("Hindi", 90);
[Link]("English", 95);
[Link]("Mathematics", 95);
[Link]("English");
[Link]();
[Link]("Hindi");
[Link]();
AcademicClass ninthB = new AcademicClass("9thB");
[Link](raj);
[Link](sumit);
Student topper = [Link]();
[Link]();
Sample Output
95
285
90
280
Raj
Note:
You can make suitable function calls and use the RUN
CODE button to check your main() method output.
SOLUTION:
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
//Your Code Goes Here..
class Person
{
private String name;
private int age;
private char gender;
private String address;
public Person(String name,int age,char gender,String
address)
{
[Link]=name;
[Link]=age;
[Link]=gender;
[Link]=address;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public char gender()
{
return gender;
}
public String address()
{
return address;
}
}
class Student extends Person
{
private Map<String,Integer>marks;
public Student(String name,int age,char gender,String address)
{
super(name,age,gender,address);
[Link]=new HashMap<>();
}
public void addMarks(String subject,int mark)
{
[Link](subject,mark);
}
public int getMarks(String subject)
{
return [Link](subject,0);
}
public int getTotalMarks()
{
return
[Link]().stream().mapToInt(Integer::intValue).sum();
}
}
class AcademicClass
{
private String className;
private List<Student> students;
public AcademicClass(String className)
{
[Link]=className;
[Link]=new ArrayList<>();
}
public String getClassName()
{
return className;
}
public void addStudent(Student student)
{
[Link](student);
}
public void addStudents(List<Student> students)
{
[Link](students);
}
public Student getTopper()
{
return
[Link]().max([Link](Student::getTotalM
arks)).orElse(null);
}
}
public class Source {
public static void main(String args[] ) throws Exception {
/* Enter your code here. Read input from STDIN. Print
output to STDOUT */
Student raj=new Student("Raj",11,'M',"Noida");
[Link]("Hindi",90);
[Link]("English",95);
[Link]("Mathematics",100);
Student sumit=new Student("sumit",10,'M',"Delhi");
[Link]("Hindi",90);
[Link]("English",95);
[Link]("Mathematics",100);
[Link]("English");
[Link]();
[Link]("Hindi");
[Link]();
AcademicClass ninthB=new AcademicClass("9thB");
[Link](raj);
[Link](sumit);
Student topper=[Link]();
[Link]();
}
}
14. Technology!
subject Coding
casino 10 points
DESCRIPTION
Your task here is to implement a Java code based on the following
specifications. Note that your code should match the specifications in a
precise manner. Consider default visibility of classes, data fields, and
methods unless mentioned otherwise.
Specifications:
class definitions:
class Technology:
data members:
int techindex
String tech
visibility: private
Implement getter and setter methods for this class with public
visibility
toString(): has been implemented for you
class TechService:
data members:
String[] techArray = {"Java", "Python", "C#", "MERN", "MEAN"}
method definition:
getAllTexts(String sentence):
return type: List<String>
visibility: public
getTechnologies(String sentence) :
return type: List<Technology>
visibility: public
Task:
class Technology:
- define class Technology according to the above specifications
class TechService:
- define the String[] techArray = {"Java", "Python", "C#", "MERN",
"MEAN"}
-Implement the below method for this class:
List<String> getAllTexts(String sentence): Fetch all
the words from the string, put it into a List<String> and return
the desired list
List<Technology> getTechnologies(String sentence): From
the sentence , fetch the technologies that are present in
the techArray, put the technologies into
a List<Technology> and return the desired list
Refer sample output for clarity
Sample Input
TechService ts = new TechService();
String sentence = "Classes on Java MERN and MEAN stack
-----------------------------------------------------------
[Link](sentence)
[Link](sentence)
Sample Output
[Classes, on, Java, MERN, and, MEAN, stack]
---------------------------------------------------------
[Technology [techindex=2, tech=Java], Technology [techindex=3,
tech=MERN], Technology [techindex=5, tech=MEAN]]"
NOTE
You can make suitable function calls and use the RUN
CODE button to check your main() method output.
SOLUTION:
NOTE: 8.3/10 MARKS
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
class Technology {
//Your Code Goes Here..
private int techindex;
private String tech;
public int getTechindex(){
return techindex;
}
public void setTechindex(int techindex){
[Link]=techindex;
}
public String getTech(){
return tech;
}
public void setTech(String tech){
[Link]=tech;
}
@Override
public String toString() {
return "Technology [techindex=" + techindex + ", tech=" +
tech + "]";
}
}
class TechService {
//Your Code Goes Here..
private String[]
techArray={"Java","Python","C#","MERN","MEAN"};
public List<String> getAllTexts(String sentence){
List<String> words=new
ArrayList<>([Link]([Link]("\\s+")));
return words;
}
public List<Technology> getTechnologies(String sentence){
List<Technology> techList=new ArrayList<>();
String[] words=[Link]("\\s+");
for(String word:words){
for(int i=0;i<[Link];i++){
if([Link](techArray[i])){
Technology tech=new Technology();
[Link](i+1);
[Link](techArray[i]);
[Link](tech);
}
}
}
return techList;
}
}
public class Source {
public static void main(String args[] ) throws Exception {
/* Enter your code here. Read input from STDIN. Print
output to STDOUT */
TechService ts=new TechService();
String sentence="Classes on Java MERN stack";
List<String> allTexts=[Link](sentence);
[Link](allTexts);
List<Technology> technologies=[Link](sentence);
[Link](technologies);
}
}
15. Galvanism
subject Coding
casino 10 points
DESCRIPTION
Problem Description:
Create a Java program that calculates electricity consumption for a set of
devices.
The ElectricalDevice class represents an electrical device with a name,
power rating (in watts), and usage hours. It can calculate its energy
consumption in kilowatt-hours (kWh).
Data Members:
name: Name of the device.
powerRating: Power rating in watts.
usageHours: Used hours.
->Create the instance of the class
Methods:
1. getName: Return the name of the device.
2. calculateConsumption: Return the consumption of electricity
for the device in kilowatt-hours (kWh).
3. use: Add the used hours by the device.
ElectricityCalculator Class:
The ElectricityCalculator class manages a list of electrical devices and
calculates the total electricity consumption.
Data Member:
devices: List of ElectricalDevice objects.
->Create the instance of the class
Methods:
1. addDevice: Add a device to the list.
2. calculateTotalConsumption: Return the total power
consumption for all devices.
Formulas:
Energy consumption in kilowatt-hours (kWh) for a device: powerRating
* usageHours / 1000.
Sample Input:
ElectricalDevice device1 = new ElectricalDevice("Laptop", 45);
ElectricalDevice device2 = new ElectricalDevice("LED TV", 100);
ElectricalDevice device3 = new ElectricalDevice("Refrigerator",
150);
ElectricityCalculator calculator = new ElectricityCalculator();
[Link](device1);
[Link](device2);
[Link](device3);
[Link](4);
[Link](3);
[Link](12);
[Link]();
Sample Output:
2.2800000000000002
Note:
You can make suitable function calls and use the "RUN CODE"
button to check your main() method output.
Ensure that your program handles various scenarios, including
different devices, usage hours, and an empty device list.
SOLUTION:
import [Link];
import [Link];
class ElectricalDevice {
private String name;
private int powerRating;
private int usageHours;
public ElectricalDevice(String name, int powerRating) {
[Link] = name;
[Link] = powerRating;
[Link] = 0;
}
public String getName() {
return name;
}
public void use(int hours) {
[Link] += hours;
}
public double calculateConsumption() {
return (powerRating * usageHours) / 1000.0;
}
}
class ElectricityCalculator {
private List<ElectricalDevice> devices;
public ElectricityCalculator() {
devices = new ArrayList<>();
}
public void addDevice(ElectricalDevice device) {
[Link](device);
}
public double calculateTotalConsumption() {
double totalConsumption = 0.0;
for (ElectricalDevice device : devices) {
totalConsumption += [Link]();
}
return totalConsumption;
}
}
public class Source {
public static void main(String[] args) throws Exception {
ElectricalDevice device1 = new
ElectricalDevice("Laptop", 45);
ElectricalDevice device2 = new ElectricalDevice("LED
TV", 100);
ElectricalDevice device3 = new
ElectricalDevice("Refrigerator", 150);
ElectricityCalculator calculator = new
ElectricityCalculator();
[Link](device1);
[Link](device2);
[Link](device3);
[Link](4);
[Link](3);
[Link](12);
double totalConsumption =
[Link]();
[Link](totalConsumption);
}
}