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

Coding Java

The document outlines several Java coding tasks, including a lift simulation system, employee sorting with enums, car site management, and finding minimum difference pairs in an array. Each task includes class definitions, methods, and sample input/output to illustrate functionality. The solutions provided include complete Java code implementations for each task.

Uploaded by

keerthanaw24a
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)
3 views48 pages

Coding Java

The document outlines several Java coding tasks, including a lift simulation system, employee sorting with enums, car site management, and finding minimum difference pairs in an array. Each task includes class definitions, methods, and sample input/output to illustrate functionality. The solutions provided include complete Java code implementations for each task.

Uploaded by

keerthanaw24a
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

CORE JAVA CODING

STIONS
1] LIFT SIMULATION WITH PASSENGER AND LIFT CLASS
Problem Statement
You are tasked with simulating a lift system that can move between different floors of a building and
transport passengers. The system should maintain its movement operations and allow for user
interaction through a command-line interface.
Class Definitions:
Passenger:
->Create a Java class named "Passenger" to represent passengers. Passengers should have the following
attributes:
destinationFloor: Represents the floor to which the passenger wants to go.
Define the getter method for the attribute.
Lift:
->Create a Java class named "Lift" to represent the lift. The lift should have the following attributes:
currentFloor : Represents the floor where the lift is currently located.
state: The state of the elevator, which can be one of the following values:
"stopped": The elevator is not moving and the doors are closed.
"moving up": The elevator is moving upwards.
"moving down": The elevator is moving downwards.
passengers: A list to keep track of passengers inside the lift.
->Initialize the Lift object with the following initial attributes:
currentFloor is set to 1 by default.
state is set to "stopped" by default.
passengers is initialized as an empty ArrayList, representing that there are no passengers inside the
elevator when it's created.
->Implement the following methods in the "Lift" class:
getCurrentFloor(): Returns the current floor where the elevator is located.
getState(): Returns the current state of the elevator (stopped, moving up, or moving down).
getPassengers(): Returns a list of passengers currently inside the elevator.
addPassenger(Passenger passenger): Adds a passenger to the lift.
move(int destinationFloor):Moves the elevator to a specified destination floor. The elevator's state is
updated based on the direction of movement. Returns true if the elevator successfully moves to the
destination floor.
openDoors(): Simulates the opening of the elevator doors on the current floor. Passengers whose
destination is the current floor exit the elevator, and a list of exiting passengers is returned.
closeDoors(): Simulates closing the lift doors after passengers have entered or exited.
Sample Input
Lift lift = new Lift();
[Link](new Passenger(5));
[Link](5);
[Link]();
List<Passenger> exitedPassengers = [Link]();
[Link]();
Sample Output
true
5
1

Solution:
package programs;

import [Link];
import [Link];
class Passenger{
private int destinationFloor;

public Passenger(int destinationFloor){


[Link] = destinationFloor;
}
public int getdestinationFloor(){
return destinationFloor;
}

}
class Lift{
private int currentFloor;
private String state;
private List <Passenger> passengers;
public Lift(){
[Link]=1;
[Link]="stopped";
[Link]=new ArrayList<>();
}
public int getCurrentFloor(){
return currentFloor;
}
public String getState(){
return state;
}
public List<Passenger> getPassengers(){
return passengers;
}
public void addPassenger(Passenger passenger){
[Link](passenger);
}
public boolean move(int destinationFloor) {
if(destinationFloor==currentFloor){
return false;
}
state=(destinationFloor>currentFloor)?"moving up":"moving down";
//update the current floor
currentFloor=destinationFloor;
state="stopped";
return true;
}
public List<Passenger> openDoors(){
List<Passenger> exitedPassengers=new ArrayList<>();
List<Passenger> remainingPassengers=new ArrayList<>();
for(Passenger passenger:passengers ){
if ([Link]() == currentFloor) {
[Link](passenger);
}

else{
[Link](passenger);

passengers=remainingPassengers;
return exitedPassengers;
}

public void closeDoors(){


[Link]("the door is closed");
}
}
public class LiftSystem{
public static void main(String[] args) {
Lift lift=new Lift();
[Link](new Passenger(5));
[Link](new Passenger(3));
boolean moved=[Link](5);
[Link](moved);
[Link]([Link]());
List<Passenger> exitedPassengers=[Link]();

[Link]([Link]());
[Link] .println([Link]());
[Link]();
}
}

Output:
PS C:\Users\Yukesh\Desktop\java-vscode> javac programs\[Link]
PS C:\Users\Yukesh\Desktop\java-vscode> java [Link]
true
5
1
5
the door is closed

2] ENUM Employee sort BYNAME & BYSALARY


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 Employee:
data fields:
name: String
salary: int
Implement a Constructor using the class variables.
Implement getter setter methods with public visibility.
class EmployeeInfo:
enum definition:
named constants: BYNAME
BYSALARY
method definitions:
sort(List<Employee> emps, final SortMethod method): Method to return sorted list by name and by
salary using SortMethod
Return type: List<Employee>
Visibility: public
isCharacterPresentInAllNames(Collection<Employee> entities, String character): method to check
if Employee list contains a name starting with a specific character
Return type: boolean
Visibility: public
Task:
Create an Employee class which has the following members:
String name;
int salary;
Define parameterized constructor.
Define getter method for all instance variables with public visibility.(getName(),...)
Define setter methods for all instance variables with public visibility.(setName(),....)
Create an EmployeeInfo class which performs following operations (as per the given requirements)
using StreamAPI:
enum SortMethod : representing a group of named constants BYNAME and BYSALARY
sort(List<Employee> emps, final SortMethod method): Method to return sorted list by name and by
salary using SortMethod
isCharacterPresentInAllNames(Collection<Employee> entities, String character): Method to check if
Employee list contains a name starting with a specific character
Implement using Lambda expressions.
Following has been done for you:
Main() method containing list of Employees
String toString() method, it's part of code stub, don't edit it else your test-cases might fail
Sample Input
List<Employee> emps = new ArrayList<>();
[Link](new Employee("Mickey", 100000));
[Link](new Employee("Timmy", 50000));
[Link](new Employee("Annny", 40000));
Sample Output
[<name: Annny salary: 40000>, <name: Mickey salary: 100000>, <name: Timmy salary: 50000>]
[<name: Annny salary: 40000>, <name: Timmy salary: 50000>, <name: Mickey salary: 100000>]
False

Solution:
package programs;

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

class Employee {
private String name;
private int salary;

// Parameterized constructor
public Employee(String name, int salary) {
[Link] = name;
[Link] = salary;
}

// Getter for name


public String getName() {
return name;
}

// Setter for name


public void setName(String name) {
[Link] = name;
}

// Getter for salary


public int getSalary() {
return salary;
}

// Setter for salary


public void setSalary(int salary) {
[Link] = salary;
}

// Overriding toString for formatted output


@Override
public String toString() {
return "<name: " + name + " salary: " + salary + ">";
}
}
class EmployeeInfo {
// Enum to define sort methods
public enum SortMethod {
BYNAME, BYSALARY
}

// Method to sort employees based on SortMethod


public List<Employee> sort(List<Employee> emps, final SortMethod method) {
return [Link]()
.sorted((e1, e2) -> {
if (method == [Link]) {
return [Link]().compareTo([Link]());
} else if (method == [Link]) {
return [Link]([Link](), [Link]());
}
return 0;
})
.collect([Link]());
}

// Method to check if a character is present in all employee names


public boolean isCharacterPresentInAllNames(Collection<Employee> entities, String character) {
return [Link]()
.allMatch(e -> [Link]().contains(character));
}
}

public class EmployeeEnumSort {


public static void main(String[] args) {
List<Employee> emps = new ArrayList<>();
[Link](new Employee("Mickey", 100000));
[Link](new Employee("Timmy", 50000));
[Link](new Employee("Annny", 40000));

EmployeeInfo employeeInfo = new EmployeeInfo();

// Sort by name
List<Employee> sortedByName = [Link](emps, [Link]);
[Link](sortedByName);

// Sort by salary
List<Employee> sortedBySalary = [Link](emps, [Link]);
[Link](sortedBySalary);

// Check if character "y" is present in all names


boolean isCharPresent = [Link](emps, "z");
[Link](isCharPresent);
}
}

OUTPUT:
PS C:\Users\Yukesh\Desktop\java-vscode> javac programs\[Link]
PS C:\Users\Yukesh\Desktop\java-vscode> java [Link]
[<name: Annny salary: 40000>, <name: Mickey salary: 100000>, <name: Timmy salary: 50000>]
[<name: Annny salary: 40000>, <name: Timmy salary: 50000>, <name: Mickey salary: 100000>]
False

3] CAR SITE MANAGEMENT


Task
class Car
- define data members according to the above specifications
-define a constructor and getters setters according to the above specifications
class Site
- define data members according to the above specifications
-define a constructor according to the above specifications
-Implement the below methods for this class:
-String addCar(Car car):
Write a code to add a given car object to the cars Array list.
The car will be added if and only if the cars list has cars less than the carLimit variable.
If it is possible to add a car then return "Car added!" else return "Site is full!".
-int getCarByType(String carType):
Write a code to count the number of cars in cars Array list with the same type as the given parameter
carType.
If the given carType is not "Petrol", "Diesel" or "Electric" then return -1 else return the count of the
cars.
-String removeCarById(int id):
Write a code to remove the car from the car's Array list if it is in the list.
If it is available and removed then return "Car out" else return "No car found"
Sample Input
Plain Text
Car car1 = new Car(1001,"Mycar1","Petrol");
Car car2 = new Car(1002,"Mycar2","mytype");
Site site = new Site(12,30);
[Link](car1);
[Link](car2);
[Link]("Petrol");
[Link](1002);
Sample Output
Plain Text
Car added!Car added!1Car out

NOTE:
You can make suitable function calls and use the RUN CODE button to check your main() method
output.
Make sure that all the strings in the return statement are case-sensitive.
For the ease CAR class is already implemented in the code stub

SOLUTION:
package programs;
import [Link];

class Car {
private int carId;
private String carName;
private String type;

// Constructor
public Car(int carId, String carName, String type) {
[Link] = carId;
[Link] = carName;
[Link] = type;
}

// Getters and Setters


public int getCarId() {
return carId;
}

public void setCarId(int carId) {


[Link] = carId;
}

public String getCarName() {


return carName;
}

public void setCarName(String carName) {


[Link] = carName;
}

public String getType() {


return type;
}

public void setType(String type) {


[Link] = type;
}
}

class Site {
private int siteId;
private int carLimit;
private ArrayList<Car> cars;

// Constructor
public Site(int siteId, int carLimit) {
[Link] = siteId;
[Link] = carLimit;
[Link] = new ArrayList<>();
}

// Method to add a car


public String addCar(Car car) {
if ([Link]() < carLimit) {
[Link](car);
return "Car added!";
} else {
return "Site is full!";
}
}

// Method to get cars by type


public int getCarByType(String carType) {
if (![Link]("Petrol") && ![Link]("Diesel") && ![Link]("Electric")) {
return -1;
}
int count = 0;
for (Car car : cars) {
if ([Link]().equals(carType)) {
count++;
}
}
return count;
}

// Method to remove a car by ID


public String removeCarById(int id) {
for (Car car : cars) {
if ([Link]() == id) {
[Link](car);
return "Car out";
}
}
return "No car found";
}
}

public class CarSiteManagement {


public static void main(String[] args) {
Car car1 = new Car(1001, "Mycar1", "Petrol");
Car car2 = new Car(1002, "Mycar2", "mytype");

Site site = new Site(12, 30);

// Adding cars
[Link]([Link](car1)); // Output: Car added!
[Link]([Link](car2)); // Output: Car added!

// Getting cars by type


[Link]([Link]("Petrol")); // Output: 1

// Removing car by ID
[Link]([Link](1002)); // Output: Car out
}
}

OUTPUT:
PS C:\Users\Yukesh\Desktop\java-vscode> java [Link]
Car added!Car added!1Car out

4]Minimum difference pair in array:


Given an array of distinct integers arr, your task here is to find all pairs of elements with the minimum
absolute difference of any two elements.
Your task 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 Main:
method definition:
minimumDifference(int[] arr):
return type: List<List<Integer>>
visibility: public
Task:
Create a class Main and implement the below given method:
List<List<Integer>> minimumDifference(int[] arr) : Return a list of pairs in ascending order(with
respect to pairs), each pair [a, b] follows
a, b are from arr
a<b
b - a equals to the minimum absolute difference of any two elements in arr
Sample Input1
arr = {4,2,1,3}
Sample Output1
[[1,2],[2,3],[3,4]]
Sample Input2
arr = {12, 2, 5, 9, 11, 22, 25}
Sample Output2
[[11, 12]]
Explanation
For Input 1: The minimum absolute difference is 1. List all pairs with difference equal to 1 in
ascending order.
NOTE
The above Sample Input and Sample Output are only for demonstration purposes and will be obtained
if you implement the main() method with all method calls accordingly.
SOLUTION:
package programs;
import [Link];
import [Link];
import [Link];

public class MinimumDifferenceInArray {


public List<List<Integer>> minimumDifference(int[] arr) {
// Sort the array to simplify finding pairs with minimum difference
[Link](arr);

// Initialize variables
List<List<Integer>> result = new ArrayList<>();
int minDiff = Integer.MAX_VALUE;

// Find the minimum difference


for (int i = 1; i < [Link]; i++) {
int diff = arr[i] - arr[i - 1];
if (diff < minDiff) {
minDiff = diff;
}
}

// Find all pairs with the minimum difference


for (int i = 1; i < [Link]; i++) {
int diff = arr[i] - arr[i - 1];
if (diff == minDiff) {
List<Integer> pair = new ArrayList<>();
[Link](arr[i - 1]);
[Link](arr[i]);
[Link](pair);
}
}

return result;
}

public static void main(String[] args) {


MinimumDifferenceInArray m = new MinimumDifferenceInArray();

// Example 1
int[] arr1 = {4, 2, 1, 3};
[Link]([Link](arr1)); // Output: [[1, 2], [2, 3], [3, 4]]

// Example 2
int[] arr2 = {12, 2, 5, 9, 11, 22, 25};
[Link]([Link](arr2)); // Output: [[11, 12]]
}
}

OUTPUT:
PS C:\Users\Yukesh\Desktop\java-vscode> java programs\[Link]
[[1, 2], [2, 3], [3, 4]]
[[11, 12]]

5]RACER GAME
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 Racer:
data member: String action int runScore
int jumpScore
int crawlScore
visibility: public

Racer(String action, int runScore, int jumpScore, int crawlScore):constructor with public visibility
method definition:
goodAt():
return : String
visibility : public
finalScore():
return : int
visibility : public

Task
class Racer
- define data members according to the above specifications
-define a constructor according to the above specifications
-The term/variable used are defined below -
action - A string that contains only 3 different characters 'r', 'j', and 'c'. Where 'r' - run, 'c' - crawl, and 'j'
- jump.
runScore - A int that denotes what score will he get for every 'r' in action string.
jumpScore - A int that denotes what score will he get for every 'j' in action string.
crawlScore - A int that denotes what score will he get for every 'c' in action string.
-Implement the below methods for this class:
-String goodAt():
Write a code that returns the string on the basis of the given conditions -
If a count of the character 'j' is equal to the count of the character 'c' in the string action then return
"Perfect".
If a count of the character 'j' is greater than the count of the character 'c' in the string action then return
"Jumper".
If a count of the character 'j' is less than the count of the character 'c' in the string action then return
"Crawler".
-int finalScore():
Return the sum of the score for each action.
For every 'r' in action, the score will be runScore.
For every 'j' in action, the score will be jumpScore.
For every 'c' in action, the score will be crawlScore.
Refer Example for better understanding
action = "jjcr" , runScore = 20, jumpScore = 30, crawlScore = 5
[Link]() returns "Jumper" as 'j' count > 'c' count in action.
[Link]() returns 85 as 20+20+5+30 = 85.
Sample Input
Racer racer = new Racer("jjccrrj",10,20,30);
[Link]();
Sample Output
Jumper
NOTE:
You can make suitable function calls and use RUN CODE button to check your main() method output.
Make sure that all the strings in the return statement are case sensitive
SOLUTION:
package programs;
public class Racer {
// Data members
private String action;
private int runScore;
private int jumpScore;
private int crawlScore;

// Constructor
public Racer(String action, int runScore, int jumpScore, int crawlScore) {
[Link] = action;
[Link] = runScore;
[Link] = jumpScore;
[Link] = crawlScore;
}

// Method to determine the racer's type


public String goodAt() {
int countJ = 0; // Count of 'j'
int countC = 0; // Count of 'c'

// Count occurrences of 'j' and 'c'


for (char ch : [Link]()) {
if (ch == 'j') {
countJ++;
} else if (ch == 'c') {
countC++;
}
}

// Determine the result based on counts


if (countJ == countC) {
return "Perfect";
} else if (countJ > countC) {
return "Jumper";
} else {
return "Crawler";
}
}

// Method to calculate the final score


public int finalScore() {
int totalScore = 0;

// Calculate total score based on the action string


for (char ch : [Link]()) {
if (ch == 'r') {
totalScore += runScore;
} else if (ch == 'j') {
totalScore += jumpScore;
} else if (ch == 'c') {
totalScore += crawlScore;
}
}

return totalScore;
}

// Main method for testing


public static void main(String[] args) {
Racer racer = new Racer("jjccrrj", 10, 20, 30);

// Test goodAt() method


[Link]([Link]()); // Output: Jumper

// Test finalScore() method


[Link]([Link]()); // Output: 140
}
}

OUTPUT:
Jumper
140

6]ELECTRIC POWER CONSUMPTION


Problem Statement
Imagine you are tasked with developing a program to manage a home electrical supply system that
comprises multiple rooms and various electrical devices. Your goal is to create a system that can turn
devices on and off, as well as measure the total power consumption within each room.
ElectricalDevice Class:
The ElectricalDevice class represents a generic electrical device and has the following data members:
deviceName: Represents the name of the device installed in a room.
powerConsumption: Represents the power consumption (in watts) of the device.
isOn: Represents whether the device is turned on or off.
You should assign values to these data elements when an ElectricalDevice object is initialized.
Implement the following methods within the ElectricalDevice class:
getPowerConsumption: This method should return the power consumption of the device, taking into
account whether it's turned on or off.
turnOn: This method is used to turn the device on.
turnOff: This method is used to turn the device off.
isOn: This method should return the status of the device (i.e., whether it is on or not).
isOff: This method should return the status of the device (i.e., whether it is off or not).
Room Class:
The Room class represents a residential room, which can be a living room, bedroom, guest room, or
any other type of room in a house.
Add the following data member to the Room class:
devices: Represent a list of devices installed in the room, such as fans, lamps, laptops, Wi-Fi routers,
and more.
name: Represents the name of the room, such as "Living Room," "Bedroom," or "Guest Room."
You should assign values to the Name data element when a Room object is initialized.
Implement the following method within the Room class:
addDevice: Add an electrical device to the room.
getTotalPowerConsumption: Calculate and return the total power consumption of all the active devices
in the room.
Total Power Consumption = Σ (Power Consumption of Each Active Device)
Sample Input
ElectricalDevice laptop = new ElectricalDevice("Laptop", 50.0);
[Link]();double laptopPowerConsumption = [Link]();
[Link]();
ElectricalDevice refrigerator = new ElectricalDevice("Refrigerator", 150.0);
[Link]();double refrigeratorPowerConsumption = [Link]();
[Link]();
Room guestRoom = new Room("Guest Room");
[Link](laptop);
[Link](refrigerator);double totalPowerConsumption =
[Link]();
[Link]();
Sample Output
50.0 150.0 200.0
NOTE:
You can make suitable function calls and use the RUN CODE button to check your main() method
output.
SOLUTION:
package programs;
import [Link];
import [Link];

class ElectricalDevice {
// Data members
private String deviceName;
private double powerConsumption;
private boolean isOn;

// Constructor
public ElectricalDevice(String deviceName, double powerConsumption) {
[Link] = deviceName;
[Link] = powerConsumption;
[Link] = false; // Default state is off
}

// Method to get the power consumption of the device


public double getPowerConsumption() {
return isOn ? powerConsumption : 0.0;
}

// Method to turn the device on


public void turnOn() {
isOn = true;
}

// Method to turn the device off


public void turnOff() {
isOn = false;
}

// Method to check if the device is on


public boolean isOn() {
return isOn;
}

// Method to check if the device is off


public boolean isOff() {
return !isOn;
}
}

class Room {
// Data members
private String name;
private List<ElectricalDevice> devices;

// Constructor
public Room(String name) {
[Link] = name;
[Link] = new ArrayList<>();
}

// Method to add a device to the room


public void addDevice(ElectricalDevice device) {
[Link](device);
}

// Method to calculate the total power consumption of all active devices


public double getTotalPowerConsumption() {
double totalPower = 0.0;
for (ElectricalDevice device : devices) {
totalPower += [Link]();
}
return totalPower;
}
}

public class ElectricPowerConsumption {


public static void main(String[] args) {
// Creating electrical devices
ElectricalDevice laptop = new ElectricalDevice("Laptop", 50.0);
[Link](); // Turn on the laptop
[Link]([Link]()); // Output: 50.0

ElectricalDevice refrigerator = new ElectricalDevice("Refrigerator", 150.0);


[Link](); // Turn on the refrigerator
[Link]([Link]()); // Output: 150.0

// Creating a room and adding devices


Room guestRoom = new Room("Guest Room");
[Link](laptop);
[Link](refrigerator);

// Calculating total power consumption in the room


[Link]([Link]()); // Output: 200.0
}
}

OUTPUT:
PS C:\Users\Yukesh\Desktop\java-vscode> java [Link]
50.0
150.0
200.0

7]COFFE SHOP PROGRAM:


Problem Statement
You are tasked with designing a program to manage orders for a coffee shop. The program should be
able to handle different types and sizes of coffee and calculate the total cost for each order. Below is
the design for this problem:
Classes:
Coffee:
->Properties:
type: The type of coffee (e.g., "Regular," "Latte," "Cappuccino," "Espresso").
size: The size of the coffee (e.g., "Small," "Medium," "Large").
quantity: The quantity of this coffee in the order.
Assign values to data elements when the object is initialized.
Order:
->Properties:
customerName: The name of the customer placing the order.
coffeeList: A list of coffee items in the order.
Initialize the order with the customer's name and the list of coffee items.
CoffeeShop:
->Constants:
PRICES: Stores the prices of different coffee types and sizes.
{2.00, 2.50, 3.00}, // Regular
{3.00, 3.50, 4.00}, // Latte
{3.50, 4.00, 4.50}, // Cappuccino
{2.50, 3.00, 3.50} // Espresso
->Methods:
calculateTotalCost(Order order): Calculate and return the total cost of the order based on the coffee
items in the order. Use the PRICES array to look up the prices of each coffee type and size.
Sample Input
List<Coffee> coffee = new ArrayList<>();
[Link](new Coffee("Regular", "Small", 27));
[Link](new Coffee("Latte", "Medium", 5));
[Link](new Coffee("Cappuccino", "Large", 3));
List<Coffee> coffee1 = new ArrayList<>();
[Link](new Coffee("Espresso", "Small", 2));
[Link](new Coffee("Latte", "Large", 1));
Order order = new Order("customer 1", coffee);
Order order1 = new Order("Customer 2", coffee1);
[Link](order));
[Link](order1));
Sample Output
85.0 9.0
NOTE:
You can make suitable function calls and use the RUN CODE button to check your main() method
output.
SOLUTION:
package programs;

import [Link];
import [Link];

// Coffee class
class Coffee {
// Properties
private String type;
private String size;
private int quantity;

// Constructor
public Coffee(String type, String size, int quantity) {
[Link] = type;
[Link] = size;
[Link] = quantity;
}

// Getters
public String getType() {
return type;
}

public String getSize() {


return size;
}

public int getQuantity() {


return quantity;
}
}

// Order class
class Order {
// Properties
private String customerName;
private List<Coffee> coffeeList;

// Constructor
public Order(String customerName, List<Coffee> coffeeList) {
[Link] = customerName;
[Link] = coffeeList;
}

// Getters
public String getCustomerName() {
return customerName;
}

public List<Coffee> getCoffeeList() {


return coffeeList;
}
}
// CoffeeShop class
class CoffeeShop {
// Constants for prices
private static final double[][] PRICES = {
{2.00, 2.50, 3.00}, // Regular
{3.00, 3.50, 4.00}, // Latte
{3.50, 4.00, 4.50}, // Cappuccino
{2.50, 3.00, 3.50} // Espresso
};

// Method to calculate total cost


public static double calculateTotalCost(Order order) {
double totalCost = 0.0;

for (Coffee coffee : [Link]()) {


int typeIndex = getTypeIndex([Link]());
int sizeIndex = getSizeIndex([Link]());

if (typeIndex != -1 && sizeIndex != -1) {


totalCost += PRICES[typeIndex][sizeIndex] * [Link]();
}
}

return totalCost;
}

// Helper method to get the index for the coffee type


private static int getTypeIndex(String type) {
switch (type) {
case "Regular":
return 0;
case "Latte":
return 1;
case "Cappuccino":
return 2;
case "Espresso":
return 3;
default:
return -1; // Invalid type
}
}

// Helper method to get the index for the coffee size


private static int getSizeIndex(String size) {
switch (size) {
case "Small":
return 0;
case "Medium":
return 1;
case "Large":
return 2;
default:
return -1; // Invalid size
}
}
}

// CoffeeShopProgram class
public class CoffeeShopProgram {
public static void main(String[] args) {
// Creating coffee lists for orders
List<Coffee> coffee = new ArrayList<>();
[Link](new Coffee("Regular", "Small", 27));
[Link](new Coffee("Latte", "Medium", 5));
[Link](new Coffee("Cappuccino", "Large", 3));

List<Coffee> coffee1 = new ArrayList<>();


[Link](new Coffee("Espresso", "Small", 2));
[Link](new Coffee("Latte", "Large", 1));

// Creating orders
Order order = new Order("Customer 1", coffee);
Order order1 = new Order("Customer 2", coffee1);

// Calculating and displaying total costs


[Link]([Link](order)); // Output: 85.0
[Link]([Link](order1)); // Output: 9.0
}
}

OUTPUT:
PS C:\Users\Yukesh\Desktop\java-vscode> java [Link]
85.0
9.0

8] SeasonalActivityOrganizer
SOLUTION:
package programs;
import [Link];
import [Link];
import [Link];
import [Link];

enum Season {
SPRING, SUMMER, AUTUMN, WINTER;
}

enum Activity {
HIKING, SWIMMING, SKIING, PUMPKIN_CARVING;
}

public class SeasonalActivityOrganizer {


private final Map<Season, EnumSet<Activity>> seasonActivities;

public SeasonalActivityOrganizer() {
seasonActivities = new HashMap<>();
// Initialize each season with an empty EnumSet
for (Season season : [Link]()) {
[Link](season, [Link]([Link]));
}
}

public Set<Activity> getActivitiesForSeason(Season season) {


EnumSet<Activity> activities = [Link](season);
if (activities == null) {
throw new IllegalArgumentException("Unknown season: " + season);
}
return activities;
}
public Set<Activity> addActivityForSeason(Activity activity, Season season) {
EnumSet<Activity> activities = [Link](season);
if (activities == null) {
throw new IllegalArgumentException("Unknown season: " + season);
}
[Link](activity);
return activities;
}

public Set<Activity> removeActivityFromAllSeasons(Activity activity) {


for (EnumSet<Activity> activities : [Link]()) {
[Link](activity);
}
return getAllActivities();
}

public Set<Activity> getAllActivities() {


EnumSet<Activity> allActivities = [Link]([Link]);
for (EnumSet<Activity> activities : [Link]()) {
[Link](activities);
}
return allActivities;
}

public static void main(String[] args) {


SeasonalActivityOrganizer organizer = new SeasonalActivityOrganizer();

// Adding activities to specific seasons


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

// Retrieve all activities


[Link]([Link]()); // [HIKING, SWIMMING, SKIING]

// Get activities for specific seasons


[Link]([Link]([Link])); // [HIKING]
[Link]([Link]([Link])); // [SWIMMING]
[Link]([Link]([Link])); // [SKIING]

// Remove an activity from all seasons


[Link]([Link]);

// Verify removal
[Link]([Link]([Link])); // []
}
}

OUTPUT:
C:\Users\Yukesh\Desktop\java-vscode> java [Link]
[HIKING, SWIMMING, SKIING]
[HIKING]
[SWIMMING]
[SKIING]
[]

9]PRODUCT COUPON VALIDATOR:


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 are public unless mentioned otherwise.
Specifications
class definitions:
class Product:
Data members:
String name;
double price;
String coupon; public Product(String name,double price,String coupon): constructor with
public visibility.
class Validator:
method definitions: validateCoupon(Product p)throws Exceptionreturn type: String
visibility: public

netPrice(Product p)
type: double
visibility: publicclass InvalidCouponException:
method definition:
InvalidCouponException(String msg)
visibility: public
Task
Class Product
- define the String variable name
- define the double variable price
- define the String variable coupon
-define the constructor as per given in the specifications.
Class Validator
Implement the below methods for this class:
-String validateCoupon(Product p):
throw an InvalidCouponException "Invalid Coupon" if the coupon is not valid. The coupon is valid if
its name and discount value are separated with '-' and the discount value should be between 10-
25(inclusive).
Example:
name = "IPhone" ; valid coupons are "IPhone-10", "IPhone-20", "IPhone-18" etc.
return "Valid Coupon" if no exception found.
-double netPrice(Product p):
netPrice = totalPrice-discountPrice.
return netPrice if Coupon is valid else return totalPrice.
Class InvalidCouponException
define custom exception class InvalidCouponException by extending the Exception class.
define a parameterised constructor with a String argument to pass the message to the super class.
Sample Input
Product obj = new Product("IPhone",25000,"IPhone-10");
Validator val = new Validator();
[Link](obj);
[Link](obj);
Sample Output
valCop = "Valid Coupon"price = 22500.0
NOTE:
You can make suitable function calls and use the RUN CODE button to check your main() method
output.

SOLUTION:
package programs;

// Product Class
class Product {
String name;
double price;
String coupon;

// Constructor
public Product(String name, double price, String coupon) {
[Link] = name;
[Link] = price;
[Link] = coupon;
}
}

// Custom Exception Class


class InvalidCouponException extends Exception {
// Constructor
public InvalidCouponException(String msg) {
super(msg);
}
}

// Validator Class
class Validator {
// Method to validate the coupon
public String validateCoupon(Product p) throws InvalidCouponException {
// Check if the coupon matches the pattern "<name>-<discount>"
if ([Link] != null && [Link]("-")) {
String[] parts = [Link]("-");
if ([Link] == 2) {
String couponName = parts[0];
try {
int discountValue = [Link](parts[1]);

// Check if the coupon name matches the product name and discount is valid
if ([Link]([Link]) && discountValue >= 10 && discountValue <= 25) {
return "Valid Coupon";
}
} catch (NumberFormatException e) {
// Invalid discount value format
}
}
}

// If validation fails, throw an exception


throw new InvalidCouponException("Invalid Coupon");
}

// Method to calculate net price


public double netPrice(Product p) {
try {
// Validate the coupon first
String validation = validateCoupon(p);

if ([Link]("Valid Coupon")) {
// Extract the discount value from the coupon
String[] parts = [Link]("-");
int discountValue = [Link](parts[1]);

// Calculate the discount price


double discountPrice = ([Link] * discountValue) / 100.0;

// Calculate and return the net price


return [Link] - discountPrice;
}
} catch (InvalidCouponException e) {
// If coupon is invalid, return the total price
}

return [Link];
}
}

// Main Class
public class ProductCouponValidator {
public static void main(String[] args) {
// Create a Product object
Product obj = new Product("IPhone", 25000, "IPhone-10");

// Create a Validator object


Validator val = new Validator();

// Validate coupon and calculate net price


try {
String valCop = [Link](obj);
[Link]("valCop = \"" + valCop + "\"");
} catch (InvalidCouponException e) {
[Link]([Link]());
}

double price = [Link](obj);


[Link]("price = " + price);
}
}

OUTPUT:
PS C:\Users\Yukesh\Desktop\java-vscode> java [Link]
valCop = "Valid Coupon"
price = 22500.0

10]EmailValidator Encryts Body Send Text


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 Email:
Variables:
Header header
String body
String greetings
Implement a parameterized constructor to initialize all the instance variables.
class Header:
Variables:
String from
String to
Implement a parameterized constructor to initialize all the instance variables.
class EmailOperations:
Methods:
emailVerify(Email e): Use regular expression to verify if the two email-ids
in the Header class is valid or not.[Return type explained in Task part].
Return type:int Visibility: public
bodyEncryption(Email e): Use Ceasar cipher(Shift-3) to encrypt the body of
the email.[To know more refer the Task part]
Return type:String Visibility:
public
greetingMessage(Email e): In this method you have to return a greeting
messgae. The greet part should be taken from greetings variable and signature(name) should be taken
from Header's 'from' email address.[To know more refer the Task part]
Return type:String
Visibility: public
Class Variables:
class Header: It contains two email id 'from' and 'to'. 'from' signifies the sender's email address and 'to'
signifies receiver's email address.
class Email: This class contains three parts: first Header header which has two email address from and
to,the second body which contains the message to send and third greetings which contains greetings
such as "Regards", "Thank you", etc.
To access a variable in Header class through Email object we use:
<Email(obj)>.<Email(variable)>.<Header(variable)>
Example to access "from" address from the Email object e we use : [Link];
Tasks:
Implement the two classes Email and Header class according to the specifications.
Implement the three methods in the EmailOperations class:
emailVerify (Email e)
bodyEncryption (Email e)
greetingMessage (Email e)
Method Description:
1. emailVerify(Email e):
In this method you have to use regex to check if the email-address to and from in Header class is valid
or not. Validation is based on:
Email address should start with alphabets(capital/small) or _(underscore).
Email address should have only one @.
Email address should end with .(dot) followed by alphabets.
e.g: amit@[Link], _ami@[Link] are valid addresses, but 1ami@[Link], amit@doselect are
invalid addresses.
Return 2 if the both email addresses are valid return 1 if one is valid, and 0 if both are invalid.

2. bodyEncryption(Email e):
In this method, you have to use Caesar cipher(shift of 3) to encrypt the body part of the Email return
the encrypted string.
Caesar shift, is one of the simplest and most widely known encryption techniques. It is a type of
substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of
positions down the alphabet. Here the number of shift is 3.
e.g: str = "Hi There Hows you", after encryption becomes "Kl Wkhuh Krzv brx". H get converted to K
that is a shift of 3 alphabets ahead.
Letters which are capital should be capital and small should be small in Encrypted message. Take care
of the spaces.

3. greetingMessage(Email e):
In this method, you have to return a concatenated string which contains the greetings variable from
Email class and Name of the person who is sending the mail(from variable in the Header class).
The name part should not contain anything which is after @ in the email id.
e.g: if greetings = "Regards" and from = "Amit@[Link]" then you have to return the message
"Regards Amit"

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:
package programs;
// Header Class
class Header {
String from;
String to;

// Constructor to initialize Header variables


public Header(String from, String to) {
[Link] = from;
[Link] = to;
}
}

// Email Class
class Email {
Header header;
String body;
String greetings;

// Constructor to initialize Email variables


public Email(Header header, String body, String greetings) {
[Link] = header;
[Link] = body;
[Link] = greetings;
}
}

// EmailOperations Class
class EmailOperations {
// Method to validate email addresses
public int emailVerify(Email e) {
String emailRegex = "^[a-zA-Z_][a-zA-Z0-9_.]*@[a-zA-Z0-9]+\\.[a-zA-Z]+$";
boolean isFromValid = [Link](emailRegex);
boolean isToValid = [Link](emailRegex);

if (isFromValid && isToValid) {


return 2; // Both email addresses are valid
} else if (isFromValid || isToValid) {
return 1; // One email address is valid
} else {
return 0; // Both email addresses are invalid
}
}

// Method to encrypt the body using Caesar cipher with shift 3


public String bodyEncryption(Email e) {
StringBuilder encryptedBody = new StringBuilder();

for (char ch : [Link]()) {


if ([Link](ch)) {
char base = [Link](ch) ? 'a' : 'A';
[Link]((char) ((ch - base + 3) % 26 + base));
} else {
[Link](ch); // Keep spaces and other characters unchanged
}
}

return [Link]();
}

// Method to create the greeting message


public String greetingMessage(Email e) {
String fromName = [Link]("@")[0]; // Extract the name part before '@'
return [Link] + " " + fromName;
}
}

// Main Class
public class EmailValidEncryptSendMessage {
public static void main(String[] args) {
// Create Header object
Header header = new Header("Amit@[Link]", "john_doe@[Link]");

// Create Email object


Email email = new Email(header, "Hi John, How are you?", "Regards");

// Create EmailOperations object


EmailOperations emailOps = new EmailOperations();

// Perform email verification


int validationStatus = [Link](email);
[Link]("Validation Status: " + validationStatus);

// Encrypt the email body


String encryptedBody = [Link](email);
[Link]("Encrypted Body: " + encryptedBody);

// Generate the greeting message


String greeting = [Link](email);
[Link]("Greeting Message: " + greeting);
}
}

OUTPUT:
PS C:\Users\Yukesh\Desktop\java-vscode> java [Link]
Validation Status: 2
Encrypted Body: Kl Mrkq, Krz duh brx?
Greeting Message: Regards Amit

11]Comments Validator for spams


Description
Complete the classes using the Specifications given below. Consider default visibility of classes, data
fields, and methods unless mentioned otherwise.
Specifications
class definitions:
class Validator:
method definitions:
checkComment(String comment) throws Exception: return type: String visibility:
public commentTheString(String comment) throws Exception:
return type: String
visibility: publicclass SpamCommentException:
method definitions:
SpamCommentException(String msg)
visibility: public
Task
Class Validator
Implement the below methods for this class:
-String checkComment(String comment):
Write a code to validate the comment.
throw a SpamCommentException, if comment has these words["abcde", "lmno", "pqrst", "wxyz"] in it,
with the message "spam comment".
throw a SpamCommentException, if a comment contains more than 2 words from the above list, with
the message "account ban due to spam comment". Note same words with a frequency of more than 2
will come in this category.
return a string message "comment is not spam" If none of the above exceptions is found.
Refer the example for better understanding.
s0 = "hello my name is steve and using abcde"
s1 = "hello my name is steve and using abcde abcde"
s2 = "hello my name is steve and using abcde lmno pqrst"
s3 = "hello my name is steve and using abcde abcde lmno"
s0 and s1 come under spam comment message.
s2 and s3 comes under the account ban message.
-String commentTheString(String comment):
Write a code to put the comment on the post.
If a checkComment method throws a SpamCommentException ,then return a message of that
exception(Use try-catch block).
If it throws any other exception then return a message "other exception".
If no exception is found then return a message "comment posted".
class SpamCommentException
-Define SpamCommentException class derived from Exception class
Sample Input
Validator obj = new Validator();-------------------------------------------[Link]("hello my
name is steve");
[Link]("my comment is safe to post");
Sample Output
comment is not spamcomment posted
NOTE:
You can make suitable function calls and use the RUN CODE button to check your main() method
output.

SOLUTION:
package programs;
// Custom Exception Class: SpamCommentException
class SpamCommentException extends Exception {
public SpamCommentException(String msg) {
super(msg);
}
}

// Validator Class
class Validator {
// Method to validate the comment
public String checkComment(String comment) throws SpamCommentException {
String[] spamWords = {"abcde", "lmno", "pqrst", "wxyz"};
String[] commentWords = [Link]("\\s+");
int spamCount = 0;

for (String word : commentWords) {


for (String spamWord : spamWords) {
if ([Link](spamWord)) {
spamCount++;
}
}
}

if (spamCount > 2) {
throw new SpamCommentException("account ban due to spam comment");
} else if (spamCount > 0) {
throw new SpamCommentException("spam comment");
}

return "comment is not spam";


}

// Method to post the comment


public String commentTheString(String comment) {
try {
// Validate the comment using checkComment method
String validationResult = checkComment(comment);
return "comment posted"; // If no exception, comment is posted
} catch (SpamCommentException e) {
return [Link](); // Return specific SpamCommentException message
} catch (Exception e) {
return "other exception"; // Handle other exceptions
}
}
}

// Main Class to Test the Code


public class CommentValidator {
public static void main(String[] args) {
Validator obj = new Validator();

try {
// Test checkComment method
[Link]([Link]("hello my name is steve"));
[Link]([Link]("hello my name is steve and using abcde abcde lmno"));
} catch (Exception e) {
[Link]([Link]());
}

// Test commentTheString method


[Link]([Link]("hello my name is steve"));
[Link]([Link]("my comment includes abcde abcde lmno"));
}
}

OUTPUT:
comment is not spam
account ban due to spam comment
comment posted
account ban due to spam comment

12]BatchNumber and Date Validator

Description
Danish has opened a seed bags selling shop. He wants to arrange the bags in the order in which a bag
expires first. These bags have a twelve-digit code where:
the first four characters are Batch Number.
The next eight digits represent the seed expiry date in YYYYMMDD format.
Write a Java code to extract the expiry date from package code and display the same along with the
Batch Number.
Validations:
Batch number is valid only if the first, second and fourth characters are letters of the alphabet
(UpperCase) and the third character is a number.
If the year is not between 2015 and 2020 (both inclusive), return false else return true.
If the month is not between 1 and 12 (both inclusive), return false else return true.
If the day is not between 1 and 31 (both inclusive), return false else return true.
Assumption:
All characters in the input string will be in UPPER CASE.
class definitions:class batchmethod definitions: lengthCheck(String str):
return type: boolean
visibilty: public

batchNumberCheck(String str):
return type: boolean
visibilty: public
yearCheck(String str)):
return type: boolean
visibilty: public
monthCheck(String str):
return type: boolean
visibilty: public
dayCheck(String str):
return type: boolean
visibilty: public
printBatchNumber(String str):
return type: String
visibilty: public
printDate(String str):
return type: String
visibilty: public
Methods to be Implemented:
lengthCheck(String str): Compute the length of string and return true if length is 12 else return false.
batchNumberCheck(String str): Check if the batch number(First four digit/letters represents the batch
number ) is correct according to the description provided, return true if correct else false.
yearCheck(String str): Check if the year( Between 2015 and 2020) is valid according to the description
provided, return true if correct else false.
monthCheck(String str): Check if the month (Between 1 and 12) is valid according to the description
provided, return true if correct else false.
dayCheck(String str): Check if the day( Between 1 and 31) is valid according to the description
provided, return true if correct else false.
printBatchNumber(String str): Check if the batch number is valid according to the description provided,
return batch number if valid else return null.
printDate(String str): Check if the date is valid according to the description provided, return date in
string(Format: DD/MM/YYYY) if valid else return null.

NOTE:
The argument str in the above methods is the CODE (e.g. BL7A20181201).
The first 4-digit/letter in the batch number and last 8-digits represents the date in YYYYMMDD format.

Solution:
package programs;

class Batch {
// Method to check if the length of the string is 12
public boolean lengthCheck(String str) {
return [Link]() == 12;
}

// Method to validate the batch number


public boolean batchNumberCheck(String str) {
if ([Link]() < 4) return false; // Ensure the batch number can be extracted
char first = [Link](0);
char second = [Link](1);
char third = [Link](2);
char fourth = [Link](3);

// Check if first, second, and fourth characters are letters, and third is a digit
return [Link](first) && [Link](second)
&& [Link](third) && [Link](fourth);
}

// Method to validate the year


public boolean yearCheck(String str) {
int year = [Link]([Link](4, 8)); // Extract year
return year >= 2015 && year <= 2020;
}

// Method to validate the month


public boolean monthCheck(String str) {
int month = [Link]([Link](8, 10)); // Extract month
return month >= 1 && month <= 12;
}

// Method to validate the day


public boolean dayCheck(String str) {
int day = [Link]([Link](10, 12)); // Extract day
return day >= 1 && day <= 31;
}

// Method to print the batch number if valid


public String printBatchNumber(String str) {
if (batchNumberCheck(str)) {
return [Link](0, 4); // Return the first 4 characters as batch number
}
return null;
}

// Method to print the date in DD/MM/YYYY format if valid


public String printDate(String str) {
if (yearCheck(str) && monthCheck(str) && dayCheck(str)) {
String year = [Link](4, 8);
String month = [Link](8, 10);
String day = [Link](10, 12);
return day + "/" + month + "/" + year; // Return the date in DD/MM/YYYY format
}
return null;
}
}

// Main class for testing


public class BatchNumDateValidator {
public static void main(String[] args) {
Batch batch = new Batch();

String code1 = "BL7A20181201"; // Example valid input


String code2 = "BL7A20211301"; // Invalid month

// Test cases
[Link]("Code: " + code1);
[Link]("Length Check: " + [Link](code1));
[Link]("Batch Number: " + [Link](code1));
[Link]("Date: " + [Link](code1));

[Link]("\nCode: " + code2);


[Link]("Length Check: " + [Link](code2));
[Link]("Batch Number: " + [Link](code2));
[Link]("Date: " + [Link](code2));
}
}

OUTPUT:
Code: BL7A20181201
Length Check: true
Batch Number: BL7A
Date: 01/12/2018

Code: BL7A20211301
Length Check: true
Batch Number: BL7A
Date: null

13]BUILEDRBRICKS
Description
Complete the classes using the Specifications given below. Consider default visibility of classes, data
fields, and methods unless mentioned otherwise.

Specifications
class definitions:
class Build:
data members: int length int width visibility : public Build(int length, int width):
constructor with public visibility
method definition: builder(int blength, int bwidth, int count) throws ShortageException,
TendorException:
return : String visibility : publicclass ShortageException extends Exception:
method definitions:
ShortageException(String msg)
visibility: publicclass TendorException extends Exception:
method definitions:
TendorException(String msg)
visibility: public
Class Build
- define all the variables according to the above specifications.
- define a constructor according to the above specifications.
Implement the below methods for this class:
-String builder(int blength, int bwidth,int count) throws ShortageException, TendorException:
Write a code that accepts the length, width, and count of the bricks available and return the result
according to the mentioned scenarios below -
If the brick length(blength) evenly divides the parameter length, brick width(bwidth) evenly divides the
parameter width, and the number of bricks required to cover the total area(length*breadth) is less than
equal to the parameter count then return "Builder!!".
If the brick length(blength) evenly divides the parameter length, brick width(bwidth) evenly divides the
parameter width, and the number of bricks required to cover the total area(length*breadth) is greater
than the parameter count then throw the ShortageException with the message "Need more bricks".
If the brick length(blength) does not evenly divides the parameter length or brick width(bwidth) does
not evenly divide the parameter width, and the number of bricks required to cover the total
area(length*breadth) is less than equal to the parameter count then throw the TendorException with the
message "Building dimension mismatched".
If the brick length(blength) does not evenly divides the parameter length or brick width(bwidth) does
not evenly divide the parameter width, and the number of bricks required to cover the total
area(length*breadth) is greater than the parameter count then throw the ShortageException with the
message "Need more bricks with dimension mismatched".
Class ShortageException
- define ShortageException class derived from the Exception class.
Class TendorException
- define TendorException class derived from the Exception class.
Sample Input
Build build = new Build(100, 100);
[Link](10,10,100);
[Link](10,10,50);
Sample Output
Builder!!ShortageException: Need more bricks
NOTE:
You can make suitable function calls and use the RUN CODE button to check your main() method
output.

Solution:
package programs;
// Exception classes
class ShortageException extends Exception {
public ShortageException(String msg) {
super(msg);
}
}

class TendorException extends Exception {


public TendorException(String msg) {
super(msg);
}
}

// Build class
class Build {
public int length;
public int width;

// Constructor
public Build(int length, int width) {
[Link] = length;
[Link] = width;
}

// Method to determine if the build is possible


public String builder(int blength, int bwidth, int count) throws ShortageException, TendorException {
int totalArea = [Link] * [Link]; // Total area of the build
int brickArea = blength * bwidth; // Area of one brick
int bricksRequired = totalArea / brickArea; // Total bricks required (if exact division is possible)

// Check if the brick dimensions evenly divide the build dimensions


boolean lengthDivisible = ([Link] % blength == 0);
boolean widthDivisible = ([Link] % bwidth == 0);

// Case 1: Dimensions match, sufficient bricks


if (lengthDivisible && widthDivisible && bricksRequired <= count) {
return "Builder!!";
}

// Case 2: Dimensions match, insufficient bricks


if (lengthDivisible && widthDivisible && bricksRequired > count) {
throw new ShortageException("Need more bricks");
}

// Case 3: Dimensions mismatch, sufficient bricks


if ((!lengthDivisible || !widthDivisible) && bricksRequired <= count) {
throw new TendorException("Building dimension mismatched");
}

// Case 4: Dimensions mismatch, insufficient bricks


if ((!lengthDivisible || !widthDivisible) && bricksRequired > count) {
throw new ShortageException("Need more bricks with dimension mismatched");
}

return ""; // Should not reach here


}
}

// Main class for testing


public class BuilderBricks {
public static void main(String[] args) {
try {
Build build = new Build(100, 100);

// Test case 1: Sufficient bricks, dimensions match


[Link]([Link](10, 10, 100));

// Test case 2: Insufficient bricks, dimensions match


[Link]([Link](10, 10, 50));
} catch (ShortageException | TendorException e) {
[Link]([Link]().getSimpleName() + ": " + [Link]());
}

try {
// Test case 3: Sufficient bricks, dimensions mismatch
Build build = new Build(100, 100);
[Link]([Link](15, 10, 100));
} catch (ShortageException | TendorException e) {
[Link]([Link]().getSimpleName() + ": " + [Link]());
}

try {
// Test case 4: Insufficient bricks, dimensions mismatch
Build build = new Build(100, 100);
[Link]([Link](15, 10, 50));
} catch (ShortageException | TendorException e) {
[Link]([Link]().getSimpleName() + ": " + [Link]());
}
}
}

OUTPUT:
Builder!!
ShortageException: Need more bricks
TendorException: Building dimension mismatched
ShortageException: Need more bricks with dimension mismatched

14]SCHOLARSHIP BASED ON PERCENTAGE OF MARKS


Description
Amit is a government employee. Indian government provides scholarships to college students on a
performance basis. Amit has been given the responsibility to assign scholarships based on student
percentage and find the total amount of scholarship.
Help Amit to complete the classes using the Specifications given below. Consider default visibility of
classes, data fields, and methods unless mentioned otherwise.
Specifications
class definitions:
class Student: data members: String name String collegeName float percentage float
scholarship visibility: private
(name, collegeName, percentage): constructor with public visibility
Define getter setters with public visibility
class Portal:
data member:
ArrayList<Student> studentList
method definitions:
assignScholarship():
return type: void

totalScholarship():
return type: float

totalMaxScholarshipOfCollege():
return type: String
Task
Class Student
- define the String variable name.
- define the String variable collegeName.
- define the float variable percentage.
- define the float variable scholarship.
-define a constructor and getter setters according to the above specifications.
Class Portal
- define the ArrayList<Student> variable studentList.
Implement the below methods for this class:
-void assignScholarship():
The scholarship is going to be assigned based on the percentage given below:
If percentage >=91, scholarship = 10000.
If percentage >= 81, scholarship = 5000.
If percentage < 81, scholarship = 0.
Set the scholarship according to the percentage in studentList.
-float totalScholarship():
Write a code to find the total scholarship going to be paid by the government.
Return the total scholarship.
Example:
studentList = [{"Steve", "IIT", 89, 5000}, {"Bob", "NIT", 94, 10000}, {"Alice", "Abcd", 59, 0}] ,
totalScholarship = 15000.
-String totalMaxScholarshipOfCollege():
Write a code to find the total scholarship of all the colleges and return the college name with the
maximum scholarship.
Example:
studentList = [{"Steve", "IIT", 89, 5000}, {"Bob", "NIT", 94, 10000}, {"Alice", "NIT", 85, 5000}]
then the collegeName = "NIT".
Sample Input
Portal obj = new Portal();
[Link](new Student("Steve", "IIT", 89));
[Link](new Student("Bob", "NIT", 94));
[Link](new Student("Alice", "Abcd", 59));
------------------------------------------------------------
[Link]();
[Link]();
[Link]();
Sample Output
15000.0NIT
NOTE:
You can make suitable function calls and use the RUN CODE button to check your main() method
output.
SOLUTION:
package programs;
import [Link];
import [Link];
import [Link];

// Student class definition


class Student {
private String name;
private String collegeName;
private float percentage;
private float scholarship;

// Constructor to initialize student details


public Student(String name, String collegeName, float percentage) {
[Link] = name;
[Link] = collegeName;
[Link] = percentage;
[Link] = 0; // Initially no scholarship
}

// Getters and setters


public String getName() {
return name;
}

public void setName(String name) {


[Link] = name;
}

public String getCollegeName() {


return collegeName;
}

public void setCollegeName(String collegeName) {


[Link] = collegeName;
}
public float getPercentage() {
return percentage;
}

public void setPercentage(float percentage) {


[Link] = percentage;
}

public float getScholarship() {


return scholarship;
}

public void setScholarship(float scholarship) {


[Link] = scholarship;
}
}

// Portal class definition


class Portal {
// List of students
ArrayList<Student> studentList = new ArrayList<>();

// Method to assign scholarships based on percentage


public void assignScholarship() {
for (Student student : studentList) {
float percentage = [Link]();
// Assign scholarship based on percentage
if (percentage >= 91) {
[Link](10000);
} else if (percentage >= 81) {
[Link](5000);
} else {
[Link](0);
}
}
}

// Method to calculate total scholarship


public float totalScholarship() {
float total = 0;
for (Student student : studentList) {
total += [Link]();
}
return total;
}

// Method to find the college with the maximum scholarship


public String totalMaxScholarshipOfCollege() {
// Map to store total scholarship by college
Map<String, Float> collegeScholarshipMap = new HashMap<>();

// Calculate total scholarship for each college


for (Student student : studentList) {
String collegeName = [Link]();
float scholarship = [Link]();
[Link](collegeName, [Link](collegeName, 0f) +
scholarship);
}

// Find the college with the maximum scholarship


String maxCollege = "";
float maxScholarship = 0;

for ([Link]<String, Float> entry : [Link]()) {


if ([Link]() > maxScholarship) {
maxScholarship = [Link]();
maxCollege = [Link]();
}
}

return maxCollege;
}
}
// Main class for testing
public class ScholarshipBasedOnPercentage {
public static void main(String[] args) {
// Create portal object
Portal obj = new Portal();

// Add students to the portal


[Link](new Student("Steve", "IIT", 89));
[Link](new Student("Bob", "NIT", 94));
[Link](new Student("Alice", "Abcd", 59));

// Assign scholarships to students


[Link]();

// Output total scholarship


[Link]([Link]()); // 15000.0

// Output college with the maximum scholarship


[Link]([Link]()); // NIT
}
}

OUTPUT:

15000.0

NIT

15]BOMB BLAST PROGRAM:


Description Complete the classes using the Specifications given below. Consider default visibility of
classes, data fields, and methods unless mentioned otherwise. Specifications class definitions: class
WalkingBoy: int stepSize int blockSize visibility : public WalkingBoy(int stepSize, int blockSize) :
Constructor with public visibility method definition: targetHit(String platform) throws
Exception: return type: String visibility: publicclass BombBlast extends Exception: method
definition: BombBlast(String msg) visibility: public Task Class WalkingBoy -define all the data
members as per the given specifications. -define the constructor with public visibility. -Implement the
below methods for this class: -String targetHit(String platform) throws Exception: Write a code that
checks whether a boy hit the target/bomb or not. platform is a string that contains alphanumeric
values. divide the platform into N block of length blockSize. For every block check if the first stepSize
character contains x in it then throw BombBlast Exception with a message "You hit the target". Else
return "Win". Class BombBlast extends Exception: -Define BombBlast class derived from the Exception
class Example for Reference stepSize = 2, blockSize = 3, platform = "1212121x212" After dividing the
platform into N blocks of blockSize = 3 -> ["121", "212", "1x2", "12"] After consedering only stepSize
for every block -> ["12", "21", "1x", "12"] 3rd block contains x. therefore it throw BombBlast exception.
Sample Input WalkingBoy boy = new WalkingBoy(2,3); [Link]("1212121x212"); Sample Output
BombBlast : You hit the target NOTE: You can make suitable function calls and use the RUN CODE
button to check your main() method output. stepSize is always less than equal to the blockSize not
possibly for the last block.
SOLUTION:
package programs;
// BombBlast class derived from Exception
class BombBlast extends Exception {
// Constructor to pass the message to the Exception class
public BombBlast(String msg) {
super(msg); // Calls the parent class constructor to set the message
}
}

// WalkingBoy class
class WalkingBoy {
// Data members
int stepSize;
int blockSize;

// Constructor
public WalkingBoy(int stepSize, int blockSize) {
[Link] = stepSize;
[Link] = blockSize;
}

// Method to check if target is hit or not


public String targetHit(String platform) throws BombBlast {
// Divide the platform string into blocks of size blockSize
int length = [Link]();
int numBlocks = (length + blockSize - 1) / blockSize; // To get the number of blocks

// Iterate over each block


for (int i = 0; i < numBlocks; i++) {
// Get the start and end indices for the current block
int start = i * blockSize;
int end = [Link](start + blockSize, length);

// Extract the block


String block = [Link](start, end);

// Consider the first 'stepSize' characters of the block


String step = [Link]() > stepSize ? [Link](0, stepSize) : block;

// Check if 'x' is in the first 'stepSize' characters


if ([Link]("x")) {
throw new BombBlast("You hit the target");
}
}

// If no 'x' found, return "Win"


return "Win";
}
}

// Main class to test the functionality


public class BombBlastProgram {
public static void main(String[] args) {
try {
// Create a WalkingBoy object with stepSize = 2 and blockSize = 3
WalkingBoy boy = new WalkingBoy(2, 3);

// Test the targetHit method with a platform string


String result = [Link]("1212121x212");

// If no exception is thrown, print the result (win or loss)


[Link](result);
} catch (BombBlast e) {
// Catch the BombBlast exception and print the message
[Link]("BombBlast : " + [Link]());
}
}
}

OUTPUT:
BombBlast : You hit the target

16]USER REGISTER VALIDATION


Description Complete the classes using the Specifications given below. Consider default visibility of
classes, data fields, and methods unless mentioned otherwise. Specifications class definitions:class
Register:method definitions:checkCredentials(String email, String pass, String cpass) throws
Exception:return type: String visibility: publicclass InvalidEmailException extends Exception:method
definitions:InvalidEmailException(String msg) visibility: publicclass InvalidPasswordException
extends Exception:method definitions:InvalidPasswordException(String msg) visibility: publicclass
PasswordNotMatchException extends Exception:method
definitions:PasswordNotMatchException(String msg) visibility: public Task class Register Implement
the below methods for this class: -String checkCredentials(String email, String pass, String cpass):
Write a code to validate credentials. Throw these exceptions considering the conditions in the same
sequence in which they are given - throw an InvalidEmailException, if the email does not contain "@"
and ".", with the message "Invalid Email". throw an InvalidPasswordException, if a pass length is less
than 6 characters, with the message "Invalid Password". throw a PasswordNotMatchException, if a
cpass is not equal to the valid pass, with a message "Password not match". If the email contains "@"
and "." in it and the pass is the same as cpass with a length greater than equal to 6 then return
"Registered". Refer the example for better understanding. email1 = "myemail@email" email2 =
"myemail@[Link]" pass = "pass1234" cpass = "pass123" email1, pass and cpass gives
InvalidEmailException as email validation fails and it has to be checked at first as per the given
sequence. email2, pass and cpass gives returns Registered. class InvalidEmailException -Define
InvalidEmailException class derived from the Exception class class InvalidPasswordException -Define
InvalidPasswordException class derived from the Exception class class PasswordNotMatchException -
Define PasswordNotMatchException class derived from the Exception class Sample Input Register
user = new Register(); [Link]("tushar@gmailcom","hiiiiii","hiiiiii"); Sample Output
InvalidEmailException: Invalid Email NOTE: You can make suitable function calls and use the RUN
CODE button to check your main() method output.
SOLUTION:
package programs;
// Custom Exception: InvalidEmailException
class InvalidEmailException extends Exception {
public InvalidEmailException(String msg) {
super(msg); // Pass the message to the parent Exception class
}
}

// Custom Exception: InvalidPasswordException


class InvalidPasswordException extends Exception {
public InvalidPasswordException(String msg) {
super(msg); // Pass the message to the parent Exception class
}
}

// Custom Exception: PasswordNotMatchException


class PasswordNotMatchException extends Exception {
public PasswordNotMatchException(String msg) {
super(msg); // Pass the message to the parent Exception class
}
}

// Register Class
class Register {

// Method to validate the credentials


public String checkCredentials(String email, String pass, String cpass) throws Exception {
// Check if email contains "@" and "."
if (![Link]("@") || ![Link](".")) {
throw new InvalidEmailException("Invalid Email");
}

// Check if password length is at least 6 characters


if ([Link]() < 6) {
throw new InvalidPasswordException("Invalid Password");
}

// Check if password matches confirm password


if (![Link](cpass)) {
throw new PasswordNotMatchException("Password not match");
}

// If all validations pass, return "Registered"


return "Registered";
}
}

// Main class to test the functionality


public class UserRegisterValidation {
public static void main(String[] args) {
try {
// Create a Register object and test the checkCredentials method
Register user = new Register();
String result = [Link]("tushar@[Link]", "hiiiiii", "hiiiiii");
// If no exception is thrown, print the result
[Link](result);
} catch (InvalidEmailException e) {
[Link]("InvalidEmailException: " + [Link]());
} catch (InvalidPasswordException e) {
[Link]("InvalidPasswordException: " + [Link]());
} catch (PasswordNotMatchException e) {
[Link]("PasswordNotMatchException: " + [Link]());
} catch (Exception e) {
[Link]("General Exception: " + [Link]());
}
}
}

OUTPUT:

Registered

17]STREAM API IN METHODS

Description This is a short exercise in using Stream API . 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 Source: method definitons: count(List<String>
list): Method to count the no. of components in arraylist return type: int visibility:
publicreturn: count of components in arraylist checkPerfect(int number): Method to check if a
number is perfect or not using IntStream return type: boolean visibility: publicreturn: true
if number is perfect else false match(List<String> list): Check if there is letter e present in any
element of Arraylist Print "Great Job that sentence does not contain e" if elements
in Arraylist doesn't contain e else print "Cant fool the system, that sentence contain
e" You don't need to implement the main() method. It has already been implemented as a part of the
test-cases. It contains an ArrayList containing Strings that will be used to create streams. Task: Create
a Source class which performs operations (as per the given requirements) using StreamApi:
count(List<String> list) Method to count the no. of components in Arraylist checkPerfect(int number)
Method to check if a number is perfect or not using IntStream.(Any number can be a Java Perfect
Number if the sum of its positive divisors excluding the number itself is equal to that number) return
true if no. is Perfect return false if the no. is not Perfect match(List<String> list): Method to check if
there is letter e present in any element of Arraylist Print "Great Job that sentence does not contain e"
if elements in Arraylist doesn't contain e Print "Cant fool the system, that sentence contain e" if
elements in Arraylist contain e Implement using Lambda expressions. NOTE Do not use any for loops
or other control structures. Use the stream API methods for your implementations, else the test-cases
might fail. You can implement the main() method to check the implementation of your methods in
the solution. Upon implementation of main() method, you can use the RUN CODE button to pass
input data in the method calls and arrive at some output.

SOLUTION:

package programs;
import [Link];
import [Link];
import [Link];

class StreamApiMethods {

// Method to count the number of components in the ArrayList


public int count(List<String> list) {
// Use stream to count the number of elements in the list
return (int) [Link]().count();
}

// Method to check if a number is perfect using IntStream


public boolean checkPerfect(int number) {
// Calculate the sum of divisors of the number excluding itself
int sum = [Link](1, number)
.filter(i -> number % i == 0)
.sum();

// Return true if the sum of divisors equals the number (perfect number)
return sum == number;
}

// Method to check if any element in the list contains the letter 'e'
public void match(List<String> list) {
// Use anyMatch to check if any element contains 'e'
boolean containsE = [Link]()
.anyMatch(s -> [Link]("e"));

// Print the appropriate message based on the result


if (containsE) {
[Link]("Cant fool the system, that sentence contain e");
} else {
[Link]("Great Job that sentence does not contain e");
}
}
}

public class StreamAPI {


public static void main(String[] args) {
// Sample data
List<String> list = [Link]("Hello", "world", "example", "java");

// Create Source object to call methods


StreamApiMethods s = new StreamApiMethods();

// Test count method


[Link]("Count: " + [Link](list)); // Output: 4

// Test checkPerfect method


[Link]("Is 6 perfect? " + [Link](6)); // Output: true
[Link]("Is 28 perfect? " + [Link](28)); // Output: true
[Link]("Is 10 perfect? " + [Link](10)); // Output: false

// Test match method


[Link](list); // Output: Cant fool the system, that sentence contain e
}
}

OUTPUT:

Count: 4

Is 6 perfect? true

Is 28 perfect? true

Is 10 perfect? false

Cant fool the system, that sentence contain e

18]PRIORITY QUEUE DEMO:

Description Problem Statement You are required to implement a Priority Queue in Java using a max-
heap data structure. A Priority Queue is a data structure that maintains a set of elements, each
associated with a priority. The priority of elements is used to determine the order in which elements
are removed from the queue. In this implementation, a higher priority corresponds to a higher value.
Your task is to implement the PriorityQueue class : PriorityQueue Class: The class maintains a list of
integers (elements) to represent the priority queue. Define a constructor that initializes an empty list.
insert: Add an element to the priority queue and then perform a heapify-up operation to maintain the
max-heap property. deleteMax(): Remove and return the element with the highest priority from the
priority queue. isEmpty(): Check if the priority queue is empty. heapifyUp() Method: Move an element
up the heap to its correct position by comparing it with its parent and swapping if necessary.
heapifyDown() Method: Move an element down the heap to its correct position by comparing it with
its children and swapping with the larger child if necessary. Sample Input PriorityQueue pq = new
PriorityQueue(); [Link](5); [Link](10); [Link](3); [Link](15); [Link]();
[Link](); [Link](); [Link](); Sample Output 15 10 5 3 NOTE: You can make
suitable function calls and use the RUN CODE button to check your main() method output.

SOLUTION:

package programs;
import [Link];
import [Link];

class PriorityQueue {
private List<Integer> heap;

// Constructor to initialize the priority queue


public PriorityQueue() {
heap = new ArrayList<>();
}

// Method to check if the priority queue is empty


public boolean isEmpty() {
return [Link]();
}

// Method to insert an element into the priority queue


public void insert(int value) {
// Add the new element to the end of the heap
[Link](value);
// Restore the max-heap property by heapifying up
heapifyUp([Link]() - 1);
}

// Method to remove and return the maximum element from the priority queue
public int deleteMax() {
if (isEmpty()) {
[Link]("Priority queue is empty.");
return -1; // Or handle it according to your logic (e.g., returning a sentinel value)
}

// The root is the maximum element


int max = [Link](0);

// Move the last element to the root


int last = [Link]([Link]() - 1);
if (!isEmpty()) {
[Link](0, last);
// Restore the max-heap property by heapifying down
heapifyDown(0);
}

return max;
}

// Method to move an element up the heap to restore the max-heap property


private void heapifyUp(int index) {
// Compare the element with its parent and swap if necessary
while (index > 0) {
int parentIndex = (index - 1) / 2;
if ([Link](index) > [Link](parentIndex)) {
// Swap the elements
swap(index, parentIndex);
index = parentIndex;
} else {
break;
}
}
}
// Method to move an element down the heap to restore the max-heap property
private void heapifyDown(int index) {
int leftChildIndex = 2 * index + 1;
int rightChildIndex = 2 * index + 2;
int largest = index;

// Check if left child exists and is larger than the current element
if (leftChildIndex < [Link]() && [Link](leftChildIndex) > [Link](largest)) {
largest = leftChildIndex;
}

// Check if right child exists and is larger than the current largest element
if (rightChildIndex < [Link]() && [Link](rightChildIndex) > [Link](largest)) {
largest = rightChildIndex;
}

// If the largest element is not the current element, swap and continue heapifying down
if (largest != index) {
swap(index, largest);
heapifyDown(largest);
}
}

// Helper method to swap two elements in the heap


private void swap(int i, int j) {
int temp = [Link](i);
[Link](i, [Link](j));
[Link](j, temp);
}
}

public class PriorityQueueDemo {


public static void main(String[] args) {
PriorityQueue pq = new PriorityQueue();

// Insert elements into the priority queue


[Link](5);
[Link](10);
[Link](3);
[Link](15);

// Delete and print the max elements


[Link]([Link]()); // 15
[Link]([Link]()); // 10
[Link]([Link]()); // 5
[Link]([Link]()); // 3

// Attempting to delete from an empty queue


[Link]([Link]()); // Will print "Priority queue is empty." and return -1
}
}

OUTPUT:

15

10

Priority queue is empty.

-1

19] TRAFFIC LIGHT DEMO


You are assigned to implement a program that simulates a traffic light system using enums in JAVA
programming. The program should display the current color of the traffic light and switch to the next
color based on a predefined sequence.
Instructions:
1. Define an enum type called TrafficColor With three constants representing the colors of a
traffic light: RED, YELLOW, and GREEN.
2. Declare a variable of type TrafficColor to store the current color of the traffic light.
3. Implement a function called nextColor that takes a TrafficColor parameter and returns the
next color in the sequence according to the traffic light pattern (RED -> GREEN ->
YELLOW -> RED).
4. In the main function, initialize the current color of the traffic light to TrafficColor.
5. Implement a function called printColor that takes a TrafficColor parameter and display the
Enum value as:
• RED: "RED"
• GREEN: "GREEN"
• YELLOW: "YELLOW"
• Note: Add '\n' for the next line after every color display.
Evaluation Parameters
Sample Input
2
2
1
Sample Output
YELLOW
GREEN
Explanation
->First, 2 define the total number of colors.
->For input purposes, we define 1 as "RED," 2 as "GREEN," and 3 as "YELLOW."
->The current color initially is "GREEN," so after the next color, it becomes "YELLOW."
->The next current color is "RED," so after the next color, it becomes "GREEN."
SOLUTION:(NEXT ONLY)

package programs;

import [Link];

// Define an enum type called TrafficColor


enum TrafficColor {
RED, GREEN, YELLOW;
}

public class TrafficLightSystemNextOnly {

// Function to return the next color in the sequence


public static TrafficColor nextColor(TrafficColor currentColor) {
switch (currentColor) {
case RED:
return [Link];
case GREEN:
return [Link];
case YELLOW:
return [Link];
default:
throw new IllegalArgumentException("Invalid TrafficColor");
}
}

// Function to map integer input to TrafficColor enum


public static TrafficColor mapToColor(int colorCode) {
switch (colorCode) {
case 1:
return [Link];
case 2:
return [Link];
case 3:
return [Link];
default:
throw new IllegalArgumentException("Invalid input: Use 1 for RED, 2 for GREEN, 3 for
YELLOW");
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

// Read the number of color inputs


[Link]("Enter the number of colors: ");
int numberOfInputs = [Link]();

// Process each input to determine the next color


[Link]("Enter the colors (1 for RED, 2 for GREEN, 3 for YELLOW):");
for (int i = 0; i < numberOfInputs; i++) {
int colorCode = [Link]();
TrafficColor currentColor = mapToColor(colorCode);
TrafficColor nextColor = nextColor(currentColor);
[Link]("Next color: " + nextColor);
}

[Link]();
}
}

OUTPUT:

Enter the number of colors: 2

Enter the colors (1 for RED, 2 for GREEN, 3 for YELLOW):

Next color: RED

Next color: GREEN

SOLUTION(TO PRINT ALL):

package programs;
import [Link];

// Define an enum type called TrafficColor


enum TrafficColor {
RED, GREEN, YELLOW;
}
public class TrafficLightSystem {
// Function to return the next color in the sequence
public static TrafficColor nextColor(TrafficColor currentColor) {
switch (currentColor) {
case RED:
return [Link];
case GREEN:
return [Link];
case YELLOW:
return [Link];
default:
return null; // This case will never be reached
}
}
// Function to print the color
public static void printColor(TrafficColor color) {
switch (color) {
case RED:
[Link]("RED");
break;
case GREEN:
[Link]("GREEN");
break;
case YELLOW:
[Link]("YELLOW");
break;
}
[Link](); // Add a new line after each color display
}

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);
// Read the total number of colors to switch through
[Link]("Enter the total number of color switches: ");
int totalSwitches = [Link]();
// Initialize the current color to GREEN as per the sample
TrafficColor currentColor = [Link];
// Loop through the number of color switches
for (int i = 0; i < totalSwitches; i++) {
// Print the current color
printColor(currentColor);
// Move to the next color
currentColor = nextColor(currentColor);
}
[Link]();
}
}

OUTPUT:
Enter the total number of color switches: 3
GREEN
YELLOW

20] Licious
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:
enum definition:
enum Type {MEAT, FISH, OTHER}

class definitions:
class Dish:
data members:
final name: String
final vegetarian: boolean
final calories: int
final type: Type
visibility: private

Dish(String name, boolean vegetarian, int calories, Type type): constructor with public visibility
Define getter with public visibility
toString(): has been implemented for you

class DishImplementation:
method definition:
getNameAndCalories(List<Dish> menu):
return type: List<Dish>
visibility: public

threeHighCaloricDish(List<Dish> menu):
return type: List<String>
visibility: public

isVegetarian(List<Dish> menu):
return type: boolean
visibility: public
Task:
class Dish:
- define class Dish according to the above specifications
class DishImplementation:
Implement the below method for this class:
• List<Dish> getNameAndCalories(List<Dish> menu): filter the dishes based on :
• type OTHERS
• calories greater than equal 200 and less than 560
put the filtered dishes into a List of Dish and return the list
• List<String> threeHighCaloricDish(List<Dish> menu): fetch the first three dishes with
calories greater than 300, put it into a list and return the list
• boolean isVegetarian(List<Dish> menu): return true if the list of dish contains vegetarian
else return false
Refer sample output for clarity
Sample Input
List<Dish> menu = [Link](
new Dish("pork",false,800,[Link]),
new Dish("french fries", true, 530,[Link]),
new Dish("rice",true,120,[Link]),
new Dish("pizza", true, 550, [Link]),
new Dish("salmon",false,450,[Link]) );

DishImplementation i = new DishImplementation();


[Link](menu)
[Link](menu)
[Link](menu)
Sample Output
[Dish{name='french fries', vegetarian=true, calories=530, type=OTHER}, Dish{name='pizza',
vegetarian=true, calories=550, type=OTHER}]
----------------------------------------------------------
[pork, french fries, pizza]
----------------------------------------------------------
true
NOTE
• You can make suitable function calls and use the RUN CODE button to check
your main() method output.

SOLUTION:
package programs;

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

// Enum Definition
enum Type {
MEAT, FISH, OTHER
}

// Dish Class Definition


class Dish {
private final String name;
private final boolean vegetarian;
private final int calories;
private final Type type;

// Constructor
public Dish(String name, boolean vegetarian, int calories, Type type) {
[Link] = name;
[Link] = vegetarian;
[Link] = calories;
[Link] = type;
}

// Getters
public String getName() {
return name;
}

public boolean isVegetarian() {


return vegetarian;
}

public int getCalories() {


return calories;
}

public Type getType() {


return type;
}

// toString method
@Override
public String toString() {
return "Dish{name='" + name + "', vegetarian=" + vegetarian + ", calories=" + calories + ", type="
+ type + "}";
}
}

// DishImplementation Class Definition


class DishImplementation {

// Method 1: Get Name and Calories based on conditions


public List<Dish> getNameAndCalories(List<Dish> menu) {
return [Link]()
.filter(dish -> [Link]() == [Link])
.filter(dish -> [Link]() >= 200 && [Link]() < 560)
.collect([Link]());
}

// Method 2: Fetch three high-calorie dishes


public List<String> threeHighCaloricDish(List<Dish> menu) {
return [Link]()
.filter(dish -> [Link]() > 300)
.sorted([Link](Dish::getCalories).reversed())
.limit(3)
.map(Dish::getName)
.collect([Link]());
}

// Method 3: Check if the menu has any vegetarian dishes


public boolean isVegetarian(List<Dish> menu) {
return [Link]().anyMatch(Dish::isVegetarian);
}
}

// Main Class

public class Licious {


public static void main(String[] args) {
// Sample Input
List<Dish> menu = [Link](
new Dish("pork", false, 800, [Link]),
new Dish("french fries", true, 530, [Link]),
new Dish("rice", true, 120, [Link]),
new Dish("pizza", true, 550, [Link]),
new Dish("salmon", false, 450, [Link])
);

// DishImplementation instance
DishImplementation dishImplementation = new DishImplementation();

// Call getNameAndCalories and display output


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

// Call threeHighCaloricDish and display output


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

// Call isVegetarian and display output


[Link]([Link](menu));
}
}

OUTPUT:

PS C:\Users\Yukesh\Desktop\java-vscode> java [Link]

[Dish{name='french fries', vegetarian=true, calories=530, type=OTHER}, Dish{name='pizza',


vegetarian=true, calories=550, type=OTHER}]

----------------------------------------------------------

[pork, pizza, french fries]

----------------------------------------------------------

True

21] Spring has come (SeasonExample)

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:
package programs;

public class SeasonExample {

// Enum Definition
public enum Season {
SPRING, SUMMER, FALL, WINTER
}

// Method to get the season based on the month


public static String getSeason(int month) {
if (month == 3 || month == 4 || month == 5) {
return [Link]();
} else if (month == 6 || month == 7 || month == 8) {
return [Link]();
} else if (month == 9 || month == 10 || month == 11) {
return [Link]();
} else if (month == 12 || month == 1 || month == 2) {
return [Link]();
} else {
throw new IllegalArgumentException("Invalid month: " + month);
}
}

// Method to print the season in the specified format


public static String printSeason(Season season) {
return [Link]() + " Season";
}

// Main Method for Testing


public static void main(String[] args) {
// Example Usage
int month = 7; // Example input for month
String seasonName = [Link](month); // Get the season
[Link]([Link]([Link](seasonName))); // Print the season
}
}

OUTPUT:
PS C:\Users\Yukesh\Desktop\java-vscode> java programs\[Link]
SUMMER Season
PS C:\Users\Yukesh\Desktop\java-vscode> java programs\[Link]
WINTER Season

22]Collections in java
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 ArrayListOps:
method definitions:
convertArrayListtoInt(int n):
return type: ArrayList<Integer>
visibilty: public
reverse(ArrayList<Integer> list):
return type: ArrayList<Integer>
visibilty: public
You don't need to implement the main() method. It has already been implemented as a part of the test-
cases. It contains an ArrayList of integers.
Task:
Your task is to create a Source and implement the following:
• convertArrayListtoInt(int n): Method to create an arrayList with number of
components n and set components to 0
• reverse(ArrayList<Integer> list): Method to Reverse list
Important:
• To check your program, you can use the main() method (in Source class) given in the stub.
You can make suitable function calls and use RUN CODE button to check your main()
function output.
Sample Input
ArrayList<Integer> list = new ArrayList<Integer>([Link](10, 25, 33, 28, 10, 12));
Sample Output
[0, 0, 0, 0]
[12, 10, 28, 33, 25, 10]

SOLUTION:
package programs;

import [Link];
import [Link];

class ArrayListOps {

// Method to create an ArrayList with 'n' components set to 0


public ArrayList<Integer> convertArrayListtoInt(int n) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
[Link](0); // Add 0 to the list 'n' times
}
return list;
}

// Method to reverse the elements of an ArrayList


public ArrayList<Integer> reverse(ArrayList<Integer> list) {
ArrayList<Integer> reversedList = new ArrayList<>(list); // Create a copy of the list
[Link](reversedList); // Reverse the copy
return reversedList;
}
}

// Renamed the Source class to ArrayListOperations2 and made it public


public class ArrayListOperations2 {
public static void main(String[] args) {
ArrayListOps ops = new ArrayListOps();

// Test convertArrayListtoInt
ArrayList<Integer> zeroList = [Link](4);
[Link](zeroList); // Expected Output: [0, 0, 0, 0]

// Test reverse
ArrayList<Integer> list = new ArrayList<>();
[Link](list, 10, 25, 33, 28, 10, 12);
ArrayList<Integer> reversedList = [Link](list);
[Link](reversedList); // Expected Output: [12, 10, 28, 33, 25, 10]
}
}

OUTPUT:
PS C:\Users\Yukesh\Desktop\java-vscode> java programs.ArrayListOperations2
[0, 0, 0, 0]
[12, 10, 28, 33, 25, 10]

You might also like