CTS JAVA Complete Solution

Download as pdf or txt
Download as pdf or txt
You are on page 1of 122

1)Hello world

public class PrintMessage

public static void main(String [] args)

System.out.println("Welcome to Java world");

2) Student Details

import java.util.Scanner;

public class Main

public static void main(String[] args)

Scanner sc=new Scanner(System.in);

System.out.println("Applicant name");

String str=sc.nextLine();

System.out.println("Marks obtained in HSC");

int num=sc.nextInt();

System.out.println("Total possible marks in HSC");

int num1=sc.nextInt();

System.out.println("Engineering cutoff mark");

float num2=sc.nextFloat();

System.out.println("Marks obtained in SSLC");

int num3=sc.nextInt();
System.out.println("Total possible marks in SSLC");

int num4=sc.nextInt();

System.out.println("Gender");

char ch=sc.next().charAt(0);

System.out.println("Your Application has been Submitted Successfully");

System.out.println("The name of the applicant: "+str);

System.out.println("Engineering Cutoff: "+num2);

System.out.println("Applicant gender: "+ch);

System.out.println("All the best for your Career");

//Fill code here

3)Runs Scored

import java.util.Scanner;

import java.util.*;

public class Main

public static void main(String[] args)

Scanner sc=new Scanner(System.in);

//Fill code here

System.out.println("Runs scored");

double a=sc.nextDouble();

System.out.println("Boundaries scored");

double b=sc.nextDouble();
System.out.println("Sixers scored");

double c=sc.nextDouble();

int run =(int)(a-((b*4)+(c*6)));

double p= ((a-run)/a)*100;

double h=Math.round(p);

System.out.println("Runs scored running between wickets "+ run);

System.out.printf("Percentage of runs scored running between wickets %.2f",h);

4)Population census

import java.util.Scanner;

public class Main

public static void main(String[] args)

Scanner sc=new Scanner(System.in);

//Fill code here

System.out.println("Enter population before 10 years");

int p = sc.nextInt();

System.out.println("Enter population after 10 years");

int q = sc.nextInt();

System.out.println("Population before 10 years "+p+"\nPopulation after 10 years

"+q+"\nIncrease in population between 10 years "+(q-p)+"\nPercentage of population increase in

10 years "+(((q-p)*100/p))+"\nPercentage of population increase in a

year"+(((((q-p)*100/p)))/10));
}

5) find the word

import java.util.Scanner;

public class Main

public static void main(String[] args)

Scanner sc=new Scanner(System.in);

//Fill code here

System.out.println("Enter the alphabet");

String s = sc.nextLine();

switch(s)

case "A" :

System.out.println("A for Apple");

break;

case "B" :

System.out.println("B for Ball");

break;

case "C" :

System.out.println("C for Cat");

break;

case "D" :

System.out.println("D for Dog");


break;

case "E" :

System.out.println("E for Elephant");

break;

default:

System.out.println(s + " is an invalid input");

sc.close();

6)Ludo King

import java.util.Scanner;

public class Main

public static void main(String[] args)

Scanner sc=new Scanner(System.in);

//Fill code here

System.out.println("Enter Alex points");

int a = sc.nextInt();

if(a < 0 || a > 50)

System.out.println(a + " is an invalid number");

System.out.println("Enter Nikil points");

int b = sc.nextInt();

if(b < 0 || b > 50)


System.out.println(b + " is an invalid number");

System.out.println("Enter Sam points");

int c = sc.nextInt();

if(c < 0 || c > 50)

System.out.println(c + " is an invalid number");

if(a > b && a > c )

System.out.println("Alex scored "+a+" points and won the game");

else if(b > c )

System.out.println("Nikil scored "+b+" points and won the game");

else

System.out.println("Sam scored "+c+" points and won the game");

sc.close();

7)Resort Booking

import java.util.Scanner;

public class Main{

public static void main(String[] args){

Scanner sc=new Scanner(System.in);

//Fill the code here

String s = sc.nextLine();

int i = 0;

while(s.charAt(i) != ':')

i++;
}

i++;

if((s.charAt(i)-'0') < 0)

System.out.println("Invalid input for number of adults");

else if((s.charAt(i+2)-'0') < 0)

System.out.println("Invalid input for number of children");

else if((s.charAt(i+4)-'0') <= 0)

System.out.println("Invalid input for number of days");

i = 0;

while(s.charAt(i) != ':')

System.out.print(s.charAt(i));

i++;

i++;

System.out.print(" your booking is confirmed and the total cost is Rs

"+((((s.charAt(i)-'0')1000 + (s.charAt(i+2)-'0')*650))(s.charAt(i+4)-'0')));

8) Find the Winner

import java.util.Scanner;

import java.util.*;

public class Main{

public static void main(String[] args){

Scanner sc=new Scanner(System.in);


LinkedHashMap<Float,String> hm=new LinkedHashMap<Float,String>();

System.out.println("Enter the number of teams");

int t = sc.nextInt();

if(t<=1){

System.out.println("Invalid input");

System.exit(0);

float min_sum =Float.MAX_VALUE;

int m= t;

float sum=0;

System.out.println("Enter the details");

for(int k=0;k<t;k++){

sum=0;

String str=sc.next();

String arr1[]= str.split(":");

int n =arr1.length;

float arr[]=new float[4];

arr[0]=Float.parseFloat(arr1[1]);

arr[1]=Float.parseFloat(arr1[2]);

arr[2]=Float.parseFloat(arr1[3]);

arr[3]=Float.parseFloat(arr1[4]);

if(arr[0]<1.0 || arr[1]<1.0 || arr[2]<1.0 || arr[3]<1.0){

System.out.println("Invalid number");

return;

}
sum = arr[0]+arr[1]+arr[2]+arr[3];

hm.put(sum,arr1[0]);

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

if(sum<min_sum)

min_sum=sum;

String minKey= hm.get(min_sum);

if(minKey.equals("Prince")){

System.out.printf("King"+" team wins the race in %.2f minutes",min_sum);

}else{

System.out.printf(minKey+" team wins the race in %.2f minutes",min_sum);

//Fill the code here

9)Alphabetical order

import java.util.*;

public class Main{

static String sortString(String str) {

char []arr = str.toCharArray();

Arrays.sort(arr);

return String.valueOf(arr);

public static void main(String[] args){


Scanner sc=new Scanner(System.in);

System.out.println("Enter the sentence");

String str= sc.nextLine();

String arr1[]= str.split(" ");

int n =arr1.length;

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

char[] chars = arr1[j].toCharArray();

for(char c : chars){

if(Character.isDigit(c)){

System.out.print(str+" is an invalid input");

return;

String arr[]=new String[n];

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

arr[i]=sortString(arr1[i]);

System.out.print(arr[i]+" ");

10)Sum of Max

import java.util.*;

public class Main{

public static void main(String[] args){


Scanner sc=new Scanner(System.in);

System.out.println("Enter the array size");

int n = sc.nextInt();

if(n<=1 || n%2!=0){

System.out.println(n +" is an invalid number");

return;

int arr[]= new int[n];

System.out.println("Enter the number");

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

arr[i]=sc.nextInt();

Arrays.sort(arr);

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

for(int d=arr.length-1;d>=0;d--){

all.add(arr[d]);

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

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

al.add(arr[j] + all.get(j));

System.out.println("The maximum number is "+Collections.max(al));

11)Incredible toys
import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class CustomerDetails {

private String customerId;

private String customerName;

private long phoneNumber;

private String emailId;

private String toyType;

private double price;

public CustomerDetails(String customerId,String customerName,long phoneNumber,String

emailId, String toyType,double price)

this.customerId=customerId;

this.customerName=customerName;

this.phoneNumber=phoneNumber;

this.emailId=emailId;

this.toyType=toyType;

this.price=price;

public String getCustomerId()

return this.customerId;

public void setCustomerId(String customerId)

{
this.customerId=customerId;

public String getCustomerName()

return this.customerName;

public void setCustomerName(String customerName)

this.customerName=customerName;

public long getPhoneNumber()

return this.phoneNumber;

public void setPhoneNumber(long phoneNumber)

this.phoneNumber=phoneNumber;

public String getEmailId()

return this.emailId;

public void setEmailId(String emailId)

this.emailId=emailId;
}

public String getToyType()

return toyType;

public void setToyType(String toyType)

this.toyType=toyType;

public double getPrice()

return this.price;

public void setPrice(double price)

this.price=price;

// Fill the code

public boolean validateCustomerId() {

String customerId=getCustomerId();

String pattern = "Incredible/[0-9]{3}/[0-9]{4}";

Pattern r = Pattern.compile(pattern);

Matcher m = r.matcher(customerId);

if(m.find())

{
return true;

return false;

public double calculateDiscount() {

double price = getPrice();

int dis=0;

toyType=toyType.toLowerCase();

switch(toyType)

case "softtoys":

dis=5;

break;

case "fidgettoys":

dis=10;

break;

case "sensorytoys":

dis=15;

break;

case "puzzles":

dis=20;

break;

return (price-(price*dis/100));

}
}

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

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);

System.out.println("Enter Customer Id");

String customerId=sc.next();

System.out.println("Enter Customer Name");

String customerName=sc.next();

System.out.println("Enter Phone Number");

long phoneNumber=sc.nextLong();

System.out.println("Enter Email Id");

String emailId=sc.next();

System.out.println("Enter type");

String toyType=sc.next();

System.out.println("Enter Price");

double price = Double.parseDouble(sc.next());

CustomerDetails cd=new

CustomerDetails(customerId,customerName,phoneNumber,emailId,toyType,price);

if(cd.validateCustomerId())

double amount=cd.calculateDiscount();

System.out.printf("Amount to be paid by the Customer %.2f",amount);


}

else{

System.out.println("Provide a proper Customer Id");

12) car showroom

public class Car {

// Fill the code

private String carId;

private String modelNumber;

private String colour;

private String transmissionType;

private String fuelType;

private String engineType;

private String bodyType;

private int engineDisplacement;

private int bootSpace;

private int seatCapacity;

public Car(String carId,String modelNumber,String colour,String transmissionType,String


fuelType,

String engineType,String bodyType, int engineDisplacement,int bootSpace,int seatCapacity)

this.carId=carId;

this.modelNumber=modelNumber;
this.colour=colour;

this.transmissionType=transmissionType;

this.fuelType=fuelType;

this.engineType=engineType;

this.bodyType=bodyType;

this.engineDisplacement=engineDisplacement;

this.bootSpace=bootSpace;

this.seatCapacity=seatCapacity;

public String getCarId()

return this.carId;

public void setCarId(String carId)

this.carId=carId;

public String getModelNumber()

return this.modelNumber;

public void setModelNumber(String modelNumber)

this.modelNumber=modelNumber;

}
public String getColour()

return this.colour;

public void setColour(String colour)

this.colour=colour;

public String getTransmissionType()

return this.transmissionType;

public void setTransmissionType(String transmissionType)

this.transmissionType=transmissionType;

public String getFuelType()

return this.fuelType;

public void setFuelType(String fuelType)

this.fuelType=fuelType;

public String getEngineType()


{

return this.engineType;

public void setEngineType(String engineType)

this.engineType=engineType;

public String getBodyType()

return this.bodyType;

public void setBodyType(String bodyType)

this.bodyType=bodyType;

public int getEngineDisplacement()

return this.engineDisplacement;

public void setEngineDisplacement(int engineDisplacement)

this.engineDisplacement=engineDisplacement;

public int getBootSpace()

{
return this.bootSpace;

public void setBootSpace(int bootSpace)

this.bootSpace=bootSpace;

public int getSeatCapacity()

return this.seatCapacity;

public void setSeatCapacity(int seatCapacity)

this.seatCapacity=seatCapacity;

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

Carutility.java

import java.util.Scanner;

public class CarUtility {

public static void main(String[] args) {

// Fill the code

Car[] carObj=createCarDetails();
int n=carObj.length;

System.out.println("No of Car Details "+n);

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

System.out.println("Car Details "+(i+1));

System.out.println("Car Id "+carObj[i].getCarId());

System.out.println("Model Number "+carObj[i].getModelNumber());

System.out.println("Colour "+carObj[i].getColour());

System.out.println("Transmission Type "+carObj[i].getTransmissionType());

System.out.println("Fuel Type "+carObj[i].getFuelType());

System.out.println("Engine Type "+carObj[i].getEngineType());

System.out.println("Body Type "+carObj[i].getBodyType());

System.out.println("Engine Displacement "+carObj[i].getEngineDisplacement());

System.out.println("Boot Space "+carObj[i].getBootSpace());

System.out.println("Seat Capacity "+carObj[i].getSeatCapacity());

public static Car[] createCarDetails(){

Scanner sc = new Scanner(System.in);

// Fill the code

System.out.println("Enter the number of car details to created");

int n=sc.nextInt();
Car[] carObj=new Car[n];

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

System.out.println("Enter Car Id");

String carId=sc.nextLine();

carId = sc.nextLine();

System.out.println("Enter Model Number");

String modelNumber=sc.nextLine();

System.out.println("Enter Colour");

String colour=sc.nextLine();

System.out.println("Enter Transmission Type");

String transmissionType=sc.nextLine();

System.out.println("Enter Fuel Type");

String fuelType=sc.nextLine();

System.out.println("Enter Engine Type");

String engineType=sc.nextLine();

System.out.println("Enter Body Type");

String bodyType=sc.nextLine();

System.out.println("Enter Engine Displacement");

int engineDisplacement=sc.nextInt();

System.out.println("Enter Boot Space");

int bootSpace=sc.nextInt();

System.out.println("Enter Seat Capacity");

int seatCapacity=sc.nextInt();

carObj[i]=new Car(carId,modelNumber, colour, transmissionType, fuelType ,


engineType, bodyType, engineDisplacement, bootSpace, seatCapacity);
}

return carObj;

13)Electricity board

public class CustomerDetails {

private String customerId;

private String customerName;

private long phoneNumber;

private String city;

private double unitsConsumed;

private double costPerUnit;

public CustomerDetails(String customerId,String customerName,long

phoneNumber,String city,double unitsConsumed,double costPerUnit){

this.customerId=customerId;

this.customerName=customerName;

this.phoneNumber=phoneNumber;

this.city=city;

this.unitsConsumed=unitsConsumed;

this.costPerUnit=costPerUnit;

public String getCustomerId(){

return customerId;

public void setCustomerId( String customerId){


this.customerId=customerId;

public String getCustomerName() {

return customerName;

public void setCustomerName( String customerName) {

this.customerName=customerName;

public long getPhoneNumber(){

return phoneNumber;

public void setPhoneNumber(long phoneNumber){

this.phoneNumber=phoneNumber;

public String getCity(){

return city;

public void setCity( String city){

this.city=city;

public double getUnitsConsumed(){

return unitsConsumed;

public void setUnitsConsumed(double unitsConsumed){

this.unitsConsumed=unitsConsumed;
}

public double getCostPerUnit(){

return costPerUnit;

public void setCustomerId(double costPerUnit){

this.costPerUnit=costPerUnit;

public double calculateElectricityBill(){

double amount = unitsConsumed * costPerUnit;

return amount;

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

import java.util.*;

public class Main {

public static void main(String[] args) {

Scanner scanner=new Scanner(System.in);

System.out.println("Enter Customer Id");

String str= scanner.nextLine();

System.out.println("Enter Customer Name");

String s2 = scanner.nextLine();

System.out.println("Enter Phone Number");

long phone = scanner.nextLong();

System.out.println("Enter City");
String city = scanner.next();

System.out.println("Enter Units Consumed");

double cu=scanner.nextDouble();

System.out.println("Enter Cost per Unit");

double cuu=scanner.nextDouble();

CustomerDetails c1= new CustomerDetails(str,s2,phone,city,cu,cuu);

System.out.println("Amount to be paid is Rs."+

String.format("%.2f",c1.calculateElectricityBill()));

14)Movie Static

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("Enter movie name");

String str= scanner.nextLine();

System.out.println("Enter no of bookings");

int bookings = scanner.nextInt();

System.out.println("Enter the available tickets");

int availableTickets = scanner.nextInt();

Ticket ticket = new Ticket();

ticket.setAvailableTickets(availableTickets);

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

System.out.println("Enter the ticketid");


int ticketId = scanner.nextInt();

System.out.println("Enter the price");

int price = scanner.nextInt();

System.out.println("Enter the no of tickets");

int tickets = scanner.nextInt();

ticket.setTicketid(ticketId);

ticket.setPrice(price);

System.out.println("Available tickets: " + ticket.getAvailableTickets());

int cost = ticket.calculateTicketCost(tickets);

if(cost>0){

System.out.println("Total amount:" + cost);}

else{

System.out.println("Tickets are not available");

return;

}if(ticket.getAvailableTickets()==0){

System.out.println("House full");

}else{

System.out.println("Available ticket after booking:" + ticket.getAvailableTickets());

}}

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

public class Ticket {

private int ticketid;


private int price;

private static int availableTickets;

public int getTicketid() {

return ticketid;

public void setTicketid(int ticketid) {

this.ticketid = ticketid;

public int getPrice() {

return price;

public void setPrice(int price) {

this.price = price;

public static int getAvailableTickets() {

return availableTickets;

public static void setAvailableTickets(int availableTickets) {

if (availableTickets > 0) {

Ticket.availableTickets = availableTickets;

}else{

Ticket.availableTickets=-1;

public int calculateTicketCost(int nooftickets) {


if (nooftickets <= availableTickets) {

availableTickets -= nooftickets;

return nooftickets * price;

} else {

return -1;

15)game card

public class CardPoints {

private int cardId;

private String holderName;

private int balancePoints;

public CardPoints(int cardId, String holderName, int balancePoints) {

this.cardId = cardId;

this.holderName = holderName;

this.balancePoints = balancePoints;

public boolean withdrawPoints(int points) {

if(balancePoints >= points) {


balancePoints -= points;

System.out.println("Balance points after used:" + balancePoints);

return true;

} else {

System.out.println("Sorry!!! No enough points");

return false;

public int getCardId() {

return cardId;

public void setCardId(int cardId) {

this.cardId = cardId;

public String getHolderName() {

return holderName;

public void setHolderName(String holderName) {

this.holderName = holderName;

}
public int getBalancePoints() {

return balancePoints;

public void setBalancePoints(int balancePoints) {

this.balancePoints = balancePoints;

import java.util.Scanner;

public class GameCardDetails {

public CardPoints getCardDetails()

Scanner sc = new Scanner(System.in);

System.out.println("Enter card id");

int cardId = sc.nextInt();

System.out.println("Enter card holder name");

String holderName = sc.next();

System.out.println("Enter balance points");

int balancePoints = sc.nextInt();

do{

if (balancePoints <= 0){


System.out.println("Balance points should be positive");

System.out.println("Enter balance points");

balancePoints = sc.nextInt();

continue;

else

break;

while(true);

return new CardPoints(cardId, holderName, balancePoints);

public int getPointUsage()

Scanner sc = new Scanner(System.in);

int pointUsage = sc.nextInt();

if (pointUsage <= 0){

System.out.println("Points should be positive");

return getPointUsage();

return pointUsage;

}
public static void main(String[] arg)

GameCardDetails gameCardDetails = new GameCardDetails();

CardPoints cp = gameCardDetails.getCardDetails();

System.out.println("Enter points should be used");

int points = gameCardDetails.getPointUsage();

cp.withdrawPoints(points);

16) doctor details

public class Doctor {

private String doctorId;

private String doctorName;

private String specialization;

private Hospital hospital;

public String getDoctorId() {

return doctorId;

public void setDoctorId(String doctorId) {

this.doctorId = doctorId;

public String getDoctorName() {


return doctorName;

public void setDoctorName(String doctorName) {

this.doctorName = doctorName;

public String getSpecialization() {

return specialization;

public void setSpecialization(String specialization) {

this.specialization = specialization;

public Hospital getHospital() {

return hospital;

public void setHospital(Hospital hospital) {

this.hospital = hospital;

public Doctor(String doctorId, String doctorName, String specialization, Hospital hospital) {

this.doctorId = doctorId;

this.doctorName = doctorName;

this.specialization = specialization;

this.hospital = hospital;

------------------------------------------------------------------------------------------------------------------------------------------
public class Hospital {
private String hospitalName;

private long contactNumber;

private String city;

public String getHospitalName() {

return hospitalName;

public long getContactNumber() {

return contactNumber;

public String getCity() {

return city;

public void setHospitalName(String hospitalName) {

this.hospitalName = hospitalName;

public void setContactNumber(long contactNumber) {

this.contactNumber = contactNumber;

public void setCity(String city) {

this.city = city;

public Hospital(String hospitalName, long contactNumber, String city) {

this.hospitalName = hospitalName;

this.contactNumber = contactNumber;

this.city = city;
}

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

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

// TODO Auto-generated method stub

Doctor doc=createDoctorDetails();

System.out.println("Doctor id:"+doc.getDoctorId());

System.out.println("Doctor name:"+doc.getDoctorName());

System.out.println("Specialization:"+doc.getSpecialization());

System.out.println("Hospital name:"+doc.getHospital().getHospitalName());

System.out.println("Contact Number:"+doc.getHospital().getContactNumber());

System.out.println("City:"+doc.getHospital().getCity());

public static Doctor createDoctorDetails() {

Scanner sc = new Scanner(System.in);

System.out.println("Enter Hospital Name");

String hName=sc.nextLine();

System.out.println("Enter Contact Number");

long cNo=sc.nextLong();

sc.nextLine();

System.out.println("Enter City");
String city=sc.nextLine();

Hospital h=new Hospital(hName,cNo,city);

System.out.println("Enter Doctor Id");

String id=sc.nextLine();

System.out.println("Enter Doctor Name");

String dName=sc.nextLine();

System.out.println("Enter Specialization");

String specialization = sc.nextLine();

Doctor doc=new Doctor(id,dName,specialization,h);

return doc;

17)Disney

public class BoatHouseBooking extends Booking{

// Fill the code

private int noOfDays;

private String foodType;

public int getNoOfDays() {

return noOfDays;

public void setNoOfDays(int noOfDays) {


this.noOfDays = noOfDays;

public String getFoodType() {

return foodType;

public void setFoodType(String foodType) {

this.foodType = foodType;

public BoatHouseBooking(String customerName, String cityName, String phoneNumber, int noOfPeople,


int noOfDays,String foodType) {

super(customerName, cityName, phoneNumber, noOfPeople);

this.noOfDays=noOfDays;

this.foodType=foodType;

public double calculateTotalAmount() {

// Fill the code

if(this.foodType.equals("NonVeg")){

return (double)(this.noOfPeople*800) + (this.noOfDays*3000)+500;

}else if(this.foodType.equals("Veg") || this.foodType.equals("VEG")){

return (double)((this.noOfPeople*800) + (this.noOfDays*3000)+250);


}

return 0.0;

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

public class BoatRideBooking extends Booking{

// Fill the code

private float noOfHours;

private String guide;

public BoatRideBooking(String customerName, String cityName, String phoneNumber, int noOfPeople,


float noOfHours, String guide) {

super(customerName, cityName, phoneNumber, noOfPeople);

this.noOfHours=noOfHours;

this.guide=guide;

public double calculateTotalAmount() {


// Fill the code

if(this.guide.equals("Yes") || this.guide.equals("yes")){

return (double)(this.noOfPeople*80) + (this.noOfHours*300) + 150;

}else if(this.guide.equals("No") || this.guide.equals("no")){

return (double)(this.noOfPeople*80) + (this.noOfHours*300);

return 0.0;

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

public abstract class Booking {

// Fill the code

protected String customerName;

protected String cityName;

protected String phoneNumber;

protected int noOfPeople;

public Booking(String customerName, String cityName, String phoneNumber, int noOfPeople) {

this.customerName = customerName;

this.cityName = cityName;

this.phoneNumber = phoneNumber;
this.noOfPeople = noOfPeople;

public String getCustomerName() {

return customerName;

public void setCustomerName(String customerName) {

this.customerName = customerName;

public String getCityName() {

return cityName;

public void setCityName(String cityName) {

this.cityName = cityName;

public String getPhoneNumber() {

return phoneNumber;

public void setPhoneNumber(String phoneNumber) {

this.phoneNumber = phoneNumber;
}

public int getNoOfPeople() {

return noOfPeople;

public void setNoOfPeople(int noOfPeople) {

this.noOfPeople = noOfPeople;

public abstract double calculateTotalAmount();

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

import java.util.Scanner;

public class UserInterface {

public static void main(String[] args) {

Scanner s = new Scanner(System.in);

// Fill the code

System.out.println("Enter the Customer Name");

String customerName = s.next();

System.out.println("Enter the City name");


String cityName = s.next();

System.out.println("Enter the phone number");

String phoneNumber = s.next();

System.out.println("Enter number of people");

int noOfPeople = s.nextInt();

System.out.println("Enter the option\n" +

"1. Boat House Booking\n" +

"2. Boat Ride Booking"

);

int option = s.nextInt();

switch (option){

case 1:

System.out.println("Enter number of days");

int noOfDays = s.nextInt();

System.out.println("Enter food type (Veg/NonVeg)");

String foodType = s.next();

BoatHouseBooking BHB = new BoatHouseBooking(

customerName,

cityName,

phoneNumber,

noOfPeople,

noOfDays,

foodType);
System.out.println("Your booking has been confirmed pay Rs."+BHB.calculateTotalAmount());

break;

case 2:

System.out.println("Enter number of hours");

float noOfHours = s.nextFloat();

System.out.println("Do you want guide (Yes/No)");

String guide = s.next();

BoatRideBooking BRB = new BoatRideBooking(

customerName,

cityName,

phoneNumber,

noOfPeople,

noOfHours,

guide

);

System.out.println("Your booking has been confirmed pay Rs."+BRB.calculateTotalAmount());

break;

}
18)College Fees

public class DayScholar extends Student{

// Fill the code

private int busNumber;

private float distance;

public DayScholar(int studentId, String studentName, String department, String gender, String category,
double collegeFee,int busNumber,float distance) {

super(studentId, studentName, department, gender, category, collegeFee);

this.busNumber=busNumber;

this.distance=distance;

public int getBusNumber() {

return busNumber;

public void setBusNumber(int busNumber) {


this.busNumber = busNumber;

public float getDistance() {

return distance;

public void setDistance(float distance) {

this.distance = distance;

public double calculateTotalFee() {

// Fill the code

int busFees=0;

if(this.distance > 30 && this.distance <= 40){

busFees=28000;

}else if(this.distance > 20 && this.distance <= 30){

busFees=20000;

}else if(this.distance > 10 && this.distance <= 20){


busFees=12000;

}else if(this.distance <= 10){

busFees=6000;

if(this.collegeFee>0){

return (double)(this.collegeFee+busFees);

return 0;

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

public abstract class Student {

// Fill the code

protected int studentId;

protected String studentName;

protected String department;

protected String gender;


protected String category;

protected double collegeFee;

public Student(int studentId, String studentName, String department, String gender, String category,
double collegeFee) {

this.studentId = studentId;

this.studentName = studentName;

this.department = department;

this.gender = gender;

this.category = category;

this.collegeFee = collegeFee;

public int getStudentId() {

return studentId;

public void setStudentId(int studentId) {

this.studentId = studentId;

}
public String getStudentName() {

return studentName;

public void setStudentName(String studentName) {

this.studentName = studentName;

public String getDepartment() {

return department;

public void setDepartment(String department) {

this.department = department;

}
public String getGender() {

return gender;

public void setGender(String gender) {

this.gender = gender;

public String getCategory() {

return category;

public void setCategory(String category) {

this.category = category;

}
public double getCollegeFee() {

return collegeFee;

public void setCollegeFee(double collegeFee) {

this.collegeFee = collegeFee;

public abstract double calculateTotalFee();

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

import java.util.Scanner;

public class UserInterface {


public static void main(String[] args) {

Scanner s = new Scanner(System.in);

// Fill the code

System.out.println("Enter Student Id");

int studentId = s.nextInt();

System.out.println("Enter Student name");

String studentName = s.next();

System.out.println("Enter Department name");

String department = s.next();

System.out.println("Enter gender");

String gender = s.next();

System.out.println("Enter category");

String category = s.next();

System.out.println("Enter College fee");

double collegeFee = s.nextDouble();

switch(category){

case "DayScholar":

System.out.println("Enter Bus number");

int busNumber = s.nextInt();

System.out.println("Enter the distance");


float distance = s.nextFloat();

DayScholar dayScholar = new DayScholar(

studentId,

studentName,

department,

gender,

category,

collegeFee,

busNumber,

distance

);

System.out.println("Total College fee is "+dayScholar.calculateTotalFee());

break;

case "Hosteller":

System.out.println("Enter the room number");

int roomNumber = s.nextInt();


System.out.println("Enter the Block name");

char blockName = s.next().charAt(0);

System.out.println("Enter the room type");

String roomType = s.next();

Hosteller hosteller = new Hosteller(

studentId,

studentName,

department,

gender,

category,

collegeFee,

roomNumber,

blockName,

roomType

);

System.out.println("Total College fee is "+hosteller.calculateTotalFee());

break;

}
}

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

public class Hosteller extends Student{

// Fill the code

private int roomNumber;

private char blockName;

private String roomType;

public Hosteller(int studentId, String studentName, String department, String gender, String category,
double collegeFee, int roomNumber, char blockName, String roomType) {

super(studentId, studentName, department, gender, category, collegeFee);

this.roomNumber=roomNumber;

this.blockName=blockName;

this.roomType=roomType;

}
@Override

public double calculateTotalFee() {

int hostelFee=0,roomTypeAmount=0;

switch (this.blockName){

case 'A':

hostelFee=60000;

if(this.roomType.equals("AC")){

roomTypeAmount=8000;

break;

case 'B':

hostelFee=50000;

if(this.roomType.equals("AC")){

roomTypeAmount=5000;

break;

case 'C':

hostelFee=40000;

if(this.roomType.equals("AC")){

roomTypeAmount=2500;

break;

}
if(this.roomType.equals("AC")){

return (double)(this.collegeFee+hostelFee+roomTypeAmount);

}else if(!this.roomType.equals("AC")){

return (double)(this.collegeFee+hostelFee);

return 0.0;

19)Departmental store

public interface BonusPoints {

// Fill the code

public abstract double calculateBonusPoints();

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

public class CustomerDetails implements BonusPoints, DoorDelivery {


// Fill the code

private String customerName;

private String phoneNumber;

private String streetName;

private double billAmount;

private int distance;

public String getCustomerName() {

return customerName;

public void setCustomerName(String customerName) {

this.customerName = customerName;

public String getPhoneNumber() {

return phoneNumber;

public void setPhoneNumber(String phoneNumber) {

this.phoneNumber = phoneNumber;

public String getStreetName() {

return streetName;

public void setStreetName(String streetName) {

this.streetName = streetName;

public double getBillAmount() {


return billAmount;

public void setBillAmount(double billAmount) {

this.billAmount = billAmount;

public int getDistance() {

return distance;

public void setDistance(int distance) {

this.distance = distance;

public CustomerDetails(String customerName, String phoneNumber, String streetName, double


billAmount,

int distance) {

this.customerName = customerName;

this.phoneNumber = phoneNumber;

this.streetName = streetName;

this.billAmount = billAmount;

this.distance = distance;

public double calculateBonusPoints() {

// Fill the code

double billAmount=this.getBillAmount();

if(billAmount<250)

{
return 0;

else

return (billAmount/10);

public double deliveryCharge() {

// Fill the code

double distance=this.getDistance();

if(distance>=25)

return (distance*8);

else if(distance>=15 && distance<25)

return (distance*5);

else

return (distance*2);

}
}

public interface DoorDelivery {

// Fill the code

public abstract double deliveryCharge();

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner (System.in);

// Fill the code

System.out.println("Enter the customer name");

String name=sc.nextLine();

System.out.println("Enter the phone number");

String phone=sc.nextLine();

System.out.println("Enter the street name");

String street=sc.nextLine();

System.out.println("Enter the bill amount");

double amount=sc.nextDouble();

sc.nextLine();

System.out.println("Enter the distance");

int distance=sc.nextInt();

CustomerDetails obj=new CustomerDetails(name,phone,street,amount,distance);


double bonus=obj.calculateBonusPoints();

double delivery=obj.deliveryCharge();

System.out.println("Customer name "+obj.getCustomerName());

System.out.println("Phone number "+obj.getPhoneNumber());

System.out.println("Street name "+obj.getStreetName());

System.out.println("Bonus points "+bonus);

System.out.println("Delivery charge "+delivery);

20)Viveks

public abstract class Bero {

protected String beroType;

protected String beroColour;

protected double price;

public String getBeroType() {

return beroType;

public void setBeroType(String beroType) {

this.beroType = beroType;

public String getBeroColour() {

return beroColour;

public void setBeroColour(String beroColour) {

this.beroColour = beroColour;
}

public double getPrice() {

return price;

public void setPrice(double price) {

this.price = price;

public Bero(String beroType, String beroColour) {

this.beroType = beroType;

this.beroColour = beroColour;

public abstract void calculatePrice();

public class CustomerDetails {

private String customerName;

private long phoneNumber;

private String address;

public String getCustomerName() {

return customerName;

public void setCustomerName(String customerName) {

this.customerName = customerName;

public long getPhoneNumber() {


return phoneNumber;

public void setPhoneNumber(long phoneNumber) {

this.phoneNumber = phoneNumber;

public String getAddress() {

return address;

public void setAddress(String address) {

this.address = address;

public CustomerDetails(String customerName, long phoneNumber, String address) {

super();

this.customerName = customerName;

this.phoneNumber = phoneNumber;

this.address = address;

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

public class Discount {

public double calculateDiscount(Bero bObj)

double price=bObj.getPrice();

double discount=0;

if(bObj instanceof SteelBero)


{

discount=price*0.1;

else if(bObj instanceof WoodenBero)

discount=price*0.15;

return discount;

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

public class SteelBero extends Bero {

private int beroHeight;

public int getBeroHeight() {

return beroHeight;

public void setBeroHeight(int beroHeight) {

this.beroHeight = beroHeight;

public SteelBero(String type, String colour, int height) {

// TODO Auto-generated constructor stub


super(type, colour);

this.beroHeight = height;

@Override

public void calculatePrice() {

int height=this.getBeroHeight();

if(height==3)

this.setPrice(5000);

else if(height==5)

this.setPrice(8000);

else if(height==7)

this.setPrice(10000);

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

public class WoodenBero extends Bero {

private String woodType;


public String getWoodType() {

return woodType;

public void setWoodType(String woodType) {

this.woodType = woodType;

public WoodenBero(String beroType, String beroColour, String woodType) {

super(beroType, beroColour);

this.woodType = woodType;

@Override

public void calculatePrice() {

// TODO Auto-generated method stub

String type=this.getWoodType();

if(type.equals("Ply Wood"))

this.setPrice(15000);

else if(type.equals("Teak Wood"))

this.setPrice(12000);

}
else if(type.equals("Engineered Wood"))

this.setPrice(10000);

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

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);

System.out.println("Enter Customer Name");

String name=sc.nextLine();

System.out.println("Enter Phone Number");

long phone=sc.nextLong();

sc.nextLine();

System.out.println("Enter Address");

String address=sc.nextLine();

System.out.println("Enter Bero Type");

String type=sc.nextLine();

System.out.println("Enter Bero Colour");

String colour=sc.nextLine();

double price=0;
Discount d=new Discount();

Bero obj;

if(type.equals("Steel Bero"))

System.out.println("Enter Bero Height");

int height=sc.nextInt();

sc.nextLine();

obj=new SteelBero(type,colour,height);

obj.calculatePrice();

price=obj.getPrice()- d.calculateDiscount(obj);

else if(type.equals("Wooden Bero"))

System.out.println("Enter Wood Type");

String wtype=sc.nextLine();

obj=new WoodenBero(type,colour,wtype);

obj.calculatePrice();

price=obj.getPrice()- d.calculateDiscount(obj);

System.out.print("Amount needs to be paid Rs.");

System.out.printf("%.2f",price);

}
21)Campus radio

//make the necessary change to make this class a Exception

public class StationNotAvailableException extends Exception{

public StationNotAvailableException(String message){

super(message);

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

import java.util.Scanner;

public class UserInterface {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Scan the radio station");

float freq = sc.nextFloat();

try{

Validator vd=new Validator();

vd.validateStation(freq);

System.out.println("Radio Station on!");

}catch(StationNotAvailableException e){

System.out.println("Radio Station not available");

// fill in the code


}

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

public class Validator {

public static boolean validateStation(float freq) throws StationNotAvailableException {

boolean flag = false;

if (freq == 91.2f || freq == 93.5f || freq == 98.9f || freq == 109.4f)

flag = true;

else{

throw new StationNotAvailableException("Radio Station not available");

// fill the logic

return flag;

22)String extract

import java.util.Scanner;
public class Main {

public static void main(String args[])

Main stringExtraction = new Main();

Scanner sc=new Scanner(System.in);

// Fill the code

System.out.println("Enter the String");

String sentence = sc.nextLine();

System.out.println("Enter First Index");

int s = sc.nextInt();

System.out.println("Enter Second Index");

int e = sc.nextInt();

System.out.println(stringExtraction.extractString(sentence,s,e));

public String extractString(String sentence,int number1,int number2)

// Fill the code


StringBuilder stringBuilder = new StringBuilder();

try{

if(number1<0 || number1 > sentence.length()){

throw new StringIndexOutOfBoundsException();

}else if(number2<0 || number2 > sentence.length()){

throw new StringIndexOutOfBoundsException();

}else if(number1>number2){

throw new StringIndexOutOfBoundsException();

else{

for (int i = number1; i < number2; i++) {

stringBuilder.append(sentence.charAt(i));

stringBuilder.append(".");

}catch (StringIndexOutOfBoundsException s){

stringBuilder.append("Extraction of String using the given index is not possible.Thanks for using the
application. ");

}finally {

stringBuilder.append("Thanks for using the application.");

return stringBuilder.toString();

}
}

23)Vega Cricket

import java.util.*;

import java.util.stream.*;

public class Main {

public static void main(String args[]){

Scanner sc=new Scanner(System.in);

ManagementUtility M=new ManagementUtility();

Map<String,Integer> playerMap=new HashMap<String,Integer>();

M.setPlayerMap(playerMap);

int z=0;

while(z!=3)

System.out.println("Select an option:");

System.out.println("1.Add player score");

System.out.println("2.Display");

System.out.println("3.Exit");

z=sc.nextInt();

String name="";

int score=0;

if(z==1)

{
System.out.println("Enter the player name");

name=sc.next();

System.out.println("Enter the score");

score=sc.nextInt();

M.addPlayerScore(name,score);

else if(z==2)

Map<String,Integer> playermap=M.getPlayerMap();

Stream<Map.Entry<String,Integer>> playerStream=playermap.entrySet().stream();

int max_score=M.maximumScore(playerStream);

if(max_score==0)

System.out.println("No players found");

else

System.out.println("The maximum score of an individual player for these match is


"+max_score);

else{

System.out.println("Thank you for using the application.");

break;

}
}

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

import java.util.Map;

import java.util.*;

import java.util.stream.Stream;

import java.util.stream.Collectors;

public class ManagementUtility {

private Map<String,Integer> playerMap;

public Map<String, Integer> getPlayerMap() {

return playerMap;

public void setPlayerMap(Map<String, Integer> playerMap) {

this.playerMap = playerMap;

public void addPlayerScore(String playerName,int score) {

Map<String, Integer> playerMap=getPlayerMap();

playerMap.put(playerName,score);

//Fill the code here


}

public static int maximumScore(Stream<Map.Entry<String,Integer>> playerStream){

//List list = playerStream.collect(Collectors.toList());

//Collections.sort(hashList, Collections.reverseOrder());

List<Integer> l=playerStream.map(Map.Entry::getValue).collect(Collectors.toList());

if(l.isEmpty())

return 0;

else{

int m=Collections.max(l);

System.out.println(m);

// Fill the code here

return m;

24)Top tier

import java.util.*;

public class Main {


public static void main(String args[]){

Scanner sc=new Scanner(System.in);

System.out.println("Enter the number of vehicles");

int n = Integer.parseInt(sc.nextLine());

VehicleUtility vh = new VehicleUtility();

vh.setVehicleMap(new HashMap<String,Double>());

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

System.out.println("Enter the vehicle name and price of Vehicle "+(i+1));

String veh=sc.nextLine();

double price=Double.parseDouble(sc.nextLine());

vh.addVehiclePriceDetails(veh,price);

Map<String,Double> polmap=vh.getVehicleMap();

char choice;

do

System.out.println("Enter the vehicle name to be searched");

String search = sc.nextLine();

if(vh.calculateCostAfterDiscount(search)!=0){

System.out.println("Price after discount for "+ search +" is


"+vh.calculateCostAfterDiscount(search));

}else{

System.out.println( "TVS Apache RTR 180 is not available currently");

System.out.println("Do you want to continue (Y/N)");


choice=sc.nextLine().charAt(0);

if((choice=='n')||(choice=='N')){

System.out.println("Thank you for using the Application");

break;

while((choice=='y')||(choice=='Y'));

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

import java.util.HashMap;

import java.util.Map;

public class VehicleUtility {

private Map<String, Double> vehicleMap = new HashMap<String, Double>();

public Map<String, Double> getVehicleMap() {

return vehicleMap;

public void setVehicleMap(Map<String, Double> vehicleMap) {

this.vehicleMap = vehicleMap;

// This method should add the vehicleName as key and the price of the
// vehicle as value into a Map

public void addVehiclePriceDetails(String vehicleName, double price) {

// fill the code

vehicleMap.put(vehicleName,price);

// This method should calculate the discount and return the selling price

// after the discount for the vehicle name passed as an argument.

public double calculateCostAfterDiscount(String vehicleName) {

if(vehicleMap.containsKey(vehicleName)){

double discount=0;

// fill the code

double sp=0;

double h=vehicleMap.get(vehicleName);

if(vehicleName.contains("TVS")){

discount=10;

}else if(vehicleName.contains("Honda")){

discount=5;

}else if(vehicleName.contains("Yamaha")){

discount=7;

sp= h*(100-discount)/100;

return sp;}

else{
return 0;

25)Global Hospital

import java.util.Scanner;

import java.util.stream.Stream;

import java.util.List;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Fill the code here

ManagementUtility mu = new ManagementUtility();

System.out.println("Enter the number of donors");

int n = Integer.parseInt(sc.nextLine());

System.out.println("Enter the donor details");

String[] Strings = new String[n];

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

String donor = sc.nextLine();

Strings[i] = donor;
}

List<Donor> res = mu.getDonorDetails(Strings);

Stream<Donor> result = mu.getStreamOfDonor(res);

System.out.println("Enter the blood group to search");

String bloodGroup = sc.nextLine();

List<String> finalResult = mu.shortlistedDonor(result,bloodGroup);

if(finalResult.size() != 0)

System.out.println("List of shortlisted donors");

finalResult.forEach(s ->{System.out.println(s);});

else

System.out.println("No donor found");

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

import java.util.ArrayList;

import java.util.Collections;

import java.util.stream.Stream;

import java.util.List;

public class ManagementUtility {


public List<Donor> getDonorDetails(String [] details) {

// Fill the code here

List<Donor> temp = new ArrayList<Donor>();

for(int i=0;i<details.length;i++)

String newTemp = details[i];

String[] splitString = newTemp.split(":");

long mb = Long.parseLong(splitString[3]);

temp.add(new Donor(splitString[0],splitString[1],splitString[2],mb));

return temp;

public Stream<Donor> getStreamOfDonor(List<Donor> donorDetails) {

// Fill the code here

return donorDetails.stream();

public List<String> shortlistedDonor(Stream<Donor> donorStream, String bloodGroup) {

// Fill the code here


List<String> result = new ArrayList<String>();

donorStream.filter(s-> s.getBloodGroup().equals(bloodGroup)).forEach(s ->


{result.add(s.getDonorName());});

Collections.sort(result);

return result;

//Don't change the skeleton

public class Donor {

private String donorId;

private String donorName;

private String bloodGroup;

private long mobileNumber;

public Donor(String id,String name,String group,long mn)

this.donorId = id;

this.donorName = name;

this.bloodGroup = group;

this.mobileNumber = mn;

public String getDonorId() {

return donorId;

}
public void setDonorId(String donorId) {

this.donorId = donorId;

public String getDonorName() {

return donorName;

public void setDonorName(String donorName) {

this.donorName = donorName;

public String getBloodGroup() {

return bloodGroup;

public void setBloodGroup(String bloodGroup) {

this.bloodGroup = bloodGroup;

public long getMobileNumber() {

return mobileNumber;

public void setMobileNumber(long mobileNumber) {

this.mobileNumber = mobileNumber;

}
26)Hyper super market

import java.util.Scanner;

import java.util.stream.Stream;

import java.util.*;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int num = 0;

ManagementUtility m=new ManagementUtility();

while(num != 3){

System.out.println("Select an option:\n1.Add Vegetable to Basket\n2.Calculate


Bill\n3.Exit");

num = sc.nextInt();

if(num == 1){

VegetableBasket vege=new VegetableBasket();

System.out.println("Enter the vegetable name");

String name=sc.next();

System.out.println("Enter weight in Kgs");

int weight = sc.nextInt();

System.out.println("Enter price per Kg");

int price = sc.nextInt();

vege.setVegetableName(name);
vege.setWeightInKgs(weight);

vege.setPricePerKg(price);

m.addToBasket(vege);

else if(num==2)

List<VegetableBasket>vegeBasketList =m.getVegetableBasketList();

if(vegeBasketList.size()==0)

System.out.println("Customer basket is empty. Please add vegetables.");

else{

Stream<VegetableBasket>vegetableBasketStream = vegeBasketList.stream();

int amount = m.calculateBill(vegetableBasketStream);

System.out.println("The estimated bill amount is Rs "+amount);

System.out.println("Thank you for using the application.");

//Don't change the skeleton


public class VegetableBasket {

private String vegetableName;

private int weightInKgs;

private int pricePerKg;

public String getVegetableName() {

return vegetableName;

public void setVegetableName(String vegetableName) {

this.vegetableName = vegetableName;

public int getWeightInKgs() {

return weightInKgs;

public void setWeightInKgs(int weightInKgs) {

this.weightInKgs = weightInKgs;

public int getPricePerKg() {

return pricePerKg;

public void setPricePerKg(int pricePerKg) {

this.pricePerKg = pricePerKg;

}
}

import java.util.List;

import java.util.stream.Stream;

import java.util.*;

import java.util.stream.Collectors;

import java.util.function.Function;

public class ManagementUtility {

private List<VegetableBasket> vegetableBasketList = new ArrayList<VegetableBasket>();;

public List<VegetableBasket> getVegetableBasketList() {

return this.vegetableBasketList;

public void setVegetableBasketList(List<VegetableBasket> vegetableBasketList) {

this.vegetableBasketList = vegetableBasketList;

public void addToBasket(VegetableBasket fbObj) {

List<VegetableBasket> vge= getVegetableBasketList();

vge.add(fbObj);

setVegetableBasketList(vge);

//Fill the code here

}
public static int calculateBill(Stream<VegetableBasket> vegetableBasketStream) {

Map<Integer, Integer> V = vegetableBasketStream.collect(Collectors.toMap(VegetableBasket->


VegetableBasket.getWeightInKgs(),VegetableBasket -> VegetableBasket.getPricePerKg()));

int amount=0;

for(Map.Entry<Integer, Integer>entry : V.entrySet()) {

amount=amount+(entry.getKey()*entry.getValue());

return amount;

27)Food cart

import java.io.File; // Import the File class

import java.io.FileNotFoundException; // Import this class to handle errors

import java.util.Scanner;

public class Main

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);

int flag=1;

try {

File myObj = new File("customer.txt");

Scanner myReader = new Scanner(myObj);


String data = myReader.nextLine();

System.out.println("Enter the mobile number");

String Value = sc.next();

while (myReader.hasNextLine())

final String lineFromFile = myReader.nextLine();

if(lineFromFile.contains(Value))

// System.out.println("customer.txt");

System.out.println(lineFromFile);

flag=0;

break;

if (flag==1)

System.out.println("No customer found");

myReader.close();

} catch (FileNotFoundException e) {
System.out.println("An error occurred.");

e.printStackTrace();

Robert:7329102839:Pizza:2:2000

Advaith:8329103940:BBQ:1:350

Thanos:9762453210:Burger:4:570

Lewi:9036524133:Pizza:2:633

Albert:6852416398:BBQ:6:2000

Rahul:6663410275:Burger:4:451

Robert:8763957410:Pizza:2:1026

Jerold:9096741023:BBQ:2:457

Virat:8078451296:Burger:4:600

Dhoni:9363021245:Pizza:2:974

Praga:7685963210:BBQ:4:540

Aravind:6241053689:Burger:4:570

Praveen:8956451203:Pizza:2:3201

Issac:6410258963:BBQ:1:2000

Manish:9512023654:Burger:4:941

Ranjith:7456899874:BBQ:1:720

Akash:6352987451:Burger:4:570

Rakesh:8090461375:Pizza:8:610

Anees:9080708090:BBQ:7:350

Alex:6501200332:Burger:4:340
28)Fuel

@FunctionalInterface

public interface FuelCalc {

public double calculateFuel(String fuelName,double litres);

import java.util.*;

public class UserInterface {

public static FuelCalc generateRate()

return (String fuelName, double litres)->

{ double price=0;

fuelName=fuelName.toLowerCase();

if(fuelName.equals("petrol"))

price=litres*90.4;

else if(fuelName.equals("diesel"))

price=litres*86.8;

return price;

};

public static void main(String [] args)

Scanner sc=new Scanner(System.in);

System.out.println("Enter the type of fuel");

String s=sc.next();

System.out.println("Enter litres");
double l=sc.nextDouble();

FuelCalc f=generateRate();

double p=f.calculateFuel(s,l);

System.out.printf("Total Cost of the fuel =Rs. %.2f",p);

29)College account

public interface TuitionFee {

int calculateTuitionFees(String courseType, int basicFee, int noOfSemesters);

import java.util.Scanner;

public class UserInterface {

public static TuitionFee generateFeeReceipt() {

return (String courseType, int basicFee, int noOfSemesters) -> {

int regularFee = basicFee * noOfSemesters;

if (courseType.equalsIgnoreCase("regular")) {

return regularFee;

} else if (courseType.equalsIgnoreCase("selfFinance")) {

return regularFee + 50000;

} else {

return 0;
}

};

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("Enter registration number");

int registrationNumber = scanner.nextInt();

System.out.println("Enter student name");

String studentName = scanner.next();

System.out.println("Enter no of semesters");

int noOfSemesters = scanner.nextInt();

System.out.println("Enter basic fee");

int basicFee = scanner.nextInt();

System.out.println("Course type");

String courseType = scanner.next();

TuitionFee tuitionFee = generateFeeReceipt();

int tuitionFeeAmount = tuitionFee.calculateTuitionFees(courseType, basicFee, noOfSemesters);

System.out.println("Fees Receipt");

System.out.println("Registration number: "+ registrationNumber);

System.out.println("Student name: " + studentName);

System.out.println(String.format("Tuition fee for %s student: %d", courseType, tuitionFeeAmount));

}
29)Water distributor

public class Container {

public String distributorName;

public int volume;

public int count;

public String getDistributorName() {

return distributorName;

public void setDistributorName(String distributorName) {

this.distributorName = distributorName;

public int getVolume() {

return volume;

public void setVolume(int volume) {

this.volume = volume;

public int getCount() {

return count;

public void setCount(int count) {

this.count = count;

public Container(String distributorName, int volume, int count) {


super();

this.distributorName = distributorName;

this.volume = volume;

this.count = count;

public interface DiscountInfo {

// Fill the code

public double calculatePayableAmount (Container containerObj);

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

import java.util.Scanner;

public class UserInterface {

public static DiscountInfo generateBillAmount() {

return(Container containerobj)->

{ double dp=0;

if(containerobj.count>=100){

if(containerobj.volume==10)

dp=(20*containerobj.count)-(.1*containerobj.count*20);

else if(containerobj.volume==25)

dp=50*containerobj.count-(.15*containerobj.count*50);

else{

if(containerobj.volume==10)
dp=(containerobj.count*20);

else if(containerobj.volume==25)

dp= (containerobj.count*50);

return dp;

};

public static void main(String args[]) {

Scanner sc=new Scanner(System.in);

System.out.println("Enter the name of the distributor");

String s=sc.next();

System.out.println("Enter the volume of the container(in litre)");

int d=sc.nextInt();

System.out.println("Enter the no of containers");

int h=sc.nextInt();

if(d==25 || d==10)

Container obj=new Container(s,d,h);

DiscountInfo k=generateBillAmount();

double g=k.calculatePayableAmount (obj);

System.out.println("Generated Bill Amount");

System.out.println("Distributor name: "+s);

System.out.printf("Amount to be paid: Rs.%.2f",g);

}
else

System.out.println("There is no Discount");

31)Book sale

// DO NOT EDIT OR ADD ANY CODE

public class Book {

private String bookName;

private String authorName;

private double bookCost;

//Setters and Getters

public String getBookName() {

return bookName;

public void setBookName(String bookName) {

this.bookName = bookName;

public String getAuthorName() {

return authorName;

public void setAuthorName(String authorName) {


this.authorName = authorName;

public double getBookCost() {

return bookCost;

public void setBookCost(double bookCost) {

this.bookCost = bookCost;

@Override

public String toString() {

return "Book [bookName=" + bookName + ", authorName=" + authorName + ",


bookCost=" + bookCost + "]";

import java.util.List;

import java.util.stream.Stream;

import java.util.*;

import java.util.Map;

import java.util.stream.Collectors;

import java.util.Collections;

public class BookUtility {

private List<Book> bookList;


public List<Book> getBookList(){

return this.bookList;

public void setBookList(List<Book> bookList){

this.bookList = bookList;

//FILL THE CODE HERE

public Stream<Book> listToStream() {

//FILL THE CODE HERE

return getBookList().stream();

public List<Double> calculateBookDiscount(Stream<Book> stream1) {

List<Double> ans = stream1.map(Book::getBookCost).collect(Collectors.toList());

Double MUTIPLY_ELEMENT=0.90;

List<Double> answer = ans.parallelStream().map(in -> in *

MUTIPLY_ELEMENT).collect(Collectors.toList());

return answer;

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

import java.util.*;

import java.util.stream.Stream;

public class UserInterface {

public static void main(String [] args)

{
Scanner sc = new Scanner(System.in);

System.out.println("Enter the number of books");

int N=sc.nextInt();

if(N>0)

List<Book> list = new ArrayList<Book>();

System.out.println("Enter book details");

sc.nextLine();

String arr[]=new String[N];

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

arr[i]=sc.nextLine();

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

Book b=new Book();

String[] word=arr[i].split(":");

b.setAuthorName(word[1]);

b.setBookName(word[0]);

double v=Double.parseDouble(word[2]);

b.setBookCost(v);

list.add(b);

BookUtility B=new BookUtility();

B.setBookList(list);
Stream<Book> stream=B.listToStream();

List<Double> answer=B.calculateBookDiscount(stream);

System.out.println("Updated Book Cost:");

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

System.out.println(answer.get(i));

else{

System.out.println("Invalid Entry");

32)Association contest

//DO NOT EDIT OR ADD ANY CODE

public class Contestant {

private String id;

private String name;

private String address;

//setters & getters

public String getId() {

return id;
}

public void setId(String id) {

this.id = id;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public String getAddress() {

return address;

public void setAddress(String address) {

this.address = address;

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

import java.util.List;

import java.util.Map;

import java.util.*;
import java.util.stream.Stream;

import java.util.stream.Collectors;

public class ContestUtility {

private List<Contestant> ContestList;

public List<Contestant> getContestList(){

return this.ContestList;

public void setContestList(List<Contestant> ContestList)

this.ContestList=ContestList;

public Stream<Contestant> changeToStream() {

List<Contestant> list = getContestList();

return list.stream();

public List searchFromDetails(Stream<Contestant> stream1,char varString) {

Map<String,String>file = stream1.collect(Collectors.toMap(Contestant-
>Contestant.getId(),Contestant->Contestant.getName()));

List<String> l = new ArrayList<String>();

for (Map.Entry<String,String> entry : file.entrySet())

String s=Character.toString(varString);

if(entry.getValue().toLowerCase().startsWith(s.toLowerCase()))
{

l.add(entry.getKey());

return l;

import java.util.*;

import java.util.stream.Stream;

public class UserInterface {


public static void main(String[] args)

Scanner sc = new Scanner(System.in);

System.out.println("Enter the number of contestant details to enter:");

int N=sc.nextInt();

if(N>0)

System.out.println("Enter the contestant details:");

List<Contestant> ContestList = new ArrayList<Contestant>();

ContestUtility C = new ContestUtility();

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

String arr=sc.next();

String[] word=arr.split("/");

String id=word[0];

String name = word[1];

String place=word[2];

Contestant c=new Contestant();

c.setId(id);

c.setName(name);

c.setAddress(place);

ContestList.add(c);

C.setContestList(ContestList);
Stream<Contestant>stream = C.changeToStream();

System.out.println("Enter character to search");

char alpha = sc.next().charAt(0);

List list=C.searchFromDetails(stream,alpha);

List<Contestant> Contest = C.getContestList();

if(list.size()!=0)

System.out.println("Filter the names which starts with "+alpha+":");

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

if(list.contains(Contest.get(i).getId()))

System.out.println("Id: "+Contest.get(i).getId()+", Name:


"+Contest.get(i).getName());

else{

System.out.println("No record found");

else{

System.out.println("Invalid");
}

33) vehicle registration

import java.util.ArrayList;

import java.util.List;

import java.util.Scanner;

public class UserInterface {

public static void main(String [] args){

Scanner sc = new Scanner(System.in);

System.out.println("Enter the number of vehicle details:");

int a = Integer.parseInt(sc.nextLine());

if (a<=0){

System.out.println("Invalid");

else{

System.out.println("Enter the vehicle details:");

String [] x = new String[a];

List<Vehicle> clm=new ArrayList<Vehicle>();

for (int j=0;j<a;j++){

x[j] =sc.nextLine();

String[] p = x[j].split("/");

Vehicle cd = new Vehicle();


cd.setVehicleNo(Integer.parseInt(p[0]));

cd.setVehicleHolderName(p[1]);

cd.setVehicleHolderAddress(p[2]);

clm.add(cd);

VehicleUtility obj = new VehicleUtility();

obj.setVehicleList(clm);

System.out.println("Enter length of the number to search");

int uh = Integer.parseInt(sc.nextLine());

List<Vehicle> ans = obj.filterVehicleDetails(obj.convertToStream(),uh);

if (ans.isEmpty()){

System.out.println("No vehicle found");

else{

System.out.println("Filter the vehicle numbers which has a length of "+uh+":");

for (int g=0;g<ans.size();g++){

System.out.println("VehicleNumber: "+ans.get(g).getVehicleNo()+", Name:


"+ans.get(g).getVehicleHolderName());

}
}

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

// DO NOT EDIT OR ADD ANY CODE

public class Vehicle {

private int vehicleNo;

private String vehicleHolderName;

private String vehicleHolderAddress;

//Setters and Getterss

public int getVehicleNo() {

return vehicleNo;

public void setVehicleNo(int vehicleNo) {

this.vehicleNo = vehicleNo;

public String getVehicleHolderName() {

return vehicleHolderName;

public void setVehicleHolderName(String vehicleHolderName) {

this.vehicleHolderName = vehicleHolderName;

public String getVehicleHolderAddress() {


return vehicleHolderAddress;

public void setVehicleHolderAddress(String vehicleHolderAddress) {

this.vehicleHolderAddress = vehicleHolderAddress;

@Override

public String toString() {

return "Vehicle [vehicleNo=" + vehicleNo + ", vehicleHolderName=" +


vehicleHolderName

+ ", vehicleHolderAddress=" + vehicleHolderAddress + "]";

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

import java.util.Comparator;

import java.util.List;

import java.util.stream.Collectors;

import java.util.stream.Stream;public class VehicleUtility {

private List<Vehicle> vehicleList;

//FILL THE CODE HERE

public List<Vehicle> getVehicleList(){

return vehicleList;

public void setVehicleList(List<Vehicle> vehicleList){


this.vehicleList=vehicleList;

public Stream<Vehicle> convertToStream() {

Stream<Vehicle> w =vehicleList.stream();

return w;

public List filterVehicleDetails(Stream<Vehicle> stream1,int length){

List<Vehicle> shot=stream1.filter(x-
>String.valueOf(x.getVehicleNo()).length()>=length).sorted(Comparator.comparingInt(Vehicle::getVehicl
eNo)).collect(Collectors.toList());

return shot;

34) Library management

//DO NOT EDIT OR ADD ANY CODE HERE

public class Book {

private String bookId;

private String bookName;

private String bookType;

private String bookCategory;

private String bookEdition;


public Book() {

super();

public Book(String bookId, String bookName, String bookType, String bookCategory, String
bookEdition) {

super();

this.bookId = bookId;

this.bookName = bookName;

this.bookType = bookType;

this.bookCategory = bookCategory;

this.bookEdition = bookEdition;

public String getBookId() {

return bookId;

public void setBookId(String bookId) {

this.bookId = bookId;

public String getBookName() {

return bookName;

}
public void setBookName(String bookName) {

this.bookName = bookName;

public String getBookType() {

return bookType;

public void setBookType(String bookType) {

this.bookType = bookType;

public String getBookEdition() {

return bookEdition;

public void setBookEdition(String bookEdition) {

this.bookEdition = bookEdition;

public String getBookCategory() {

return bookCategory;

public void setBookCategory(String bookCategory) {

this.bookCategory = bookCategory;

}
------------------------------------------------------------------------------------------------------------------------------------

import java.util.ArrayList;

import java.util.List;

public class BookUtility implements Runnable{

private List<Book> bookList = new ArrayList<Book>();

private String searchbookName;

private int counter;

//FILL THE CODE HERE

public List<Book> getBookList(){

return bookList;

public String getSearchbookName(){

return searchbookName;

public void setBookList(List<Book> a){

this.bookList=a;

public void setSearchbookName(String x){

this.searchbookName=x;

public int getCounter(){


return counter;

public void setCounter(int counter){

this.counter=counter;

public void toValidateBookType(Book obj) throws InvalidBookException{

//FILL THE CODE

if (obj.getBookType().compareToIgnoreCase("Engineering")==0){

bookList.add(obj);

else{

throw new InvalidBookException("Book type Invalid");

public void run(){

//FILL THE CODE HERE

int count=0;

for(int j=0;j<bookList.size();j++){

if (bookList.get(j).getBookName().compareToIgnoreCase(searchbookName)==0){

count=count+1;
}

if (count==0) {

System.out.println("No Books found");

else {

System.out.println("Count of books in the library with the book name


"+searchbookName.toUpperCase()+" is "+count);

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

public class InvalidBookException extends Exception{

//FILL THE CODE

String s;

public InvalidBookException (String s){

super(s);

}
}

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

import java.util.ArrayList;

import java.util.List;

import java.util.Scanner;public class UserInterface {

public static void main(String [] args){

Scanner sc=new Scanner(System.in);

BookUtility ans = new BookUtility();

// FILL THE CODE HERE

System.out.println("Enter the number of entries");

int a = Integer.parseInt(sc.nextLine());

System.out.println("Enter the bookId/bookName/bookType/bookCategory/bookEdition");

String [] x = new String[a];

List<Book> clm=new ArrayList<Book>();

boolean flag = false;

for (int j =0;j<a;j++){

x[j] =sc.nextLine();

String[] p = x[j].split("/");

Book cd= new Book();

cd.setBookId(p[0]);

cd.setBookName(p[1]);

cd.setBookType(p[2]);

cd.setBookCategory(p[3]);

cd.setBookEdition(p[4]);

try{
ans.toValidateBookType(cd);

clm.add(cd);

catch(InvalidBookException e){

flag=true;

System.out.println(e.getMessage());

if (flag==false){

ans.setBookList(clm);

System.out.println("Print the book details");

for(int y=0;y<clm.size();y++){

System.out.println("bookId="+clm.get(y).getBookId()+",
bookName="+clm.get(y).getBookName()+", bookType="+clm.get(y).getBookType());

System.out.println("Enter book name to search");

String hh = sc.nextLine();

ans.setSearchbookName(hh);

Thread myThread = new Thread(ans);

myThread.run();

}
}

You might also like