0% found this document useful (0 votes)
8 views16 pages

Java PPA Solution - Colaboratory

The document contains multiple Java programming tasks that require implementing various classes and methods. Each task focuses on specific functionalities such as rectangle area calculation, character display at even indices, calculator operations, point comparison, singleton pattern for voting, frequency counting in character arrays, and account validation with unique constraints. The tasks involve using Java concepts like classes, inheritance, interfaces, collections, and method overriding.

Uploaded by

Rituparna Das
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)
8 views16 pages

Java PPA Solution - Colaboratory

The document contains multiple Java programming tasks that require implementing various classes and methods. Each task focuses on specific functionalities such as rectangle area calculation, character display at even indices, calculator operations, point comparison, singleton pattern for voting, frequency counting in character arrays, and account validation with unique constraints. The tasks involve using Java concepts like classes, inheritance, interfaces, collections, and method overriding.

Uploaded by

Rituparna Das
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
You are on page 1/ 16

W02PPA1

Consider the program given below. Complete the program according to the instructions provided in the comments such that the program
satisfies the given test cases.

import java.util.*;
class Rectangle{
int w; //width
int h; //height
//LINE-1: write the function setw(int) to initialize w
public void setw(int x){
w= x;
}

//LINE-2: write the function seth(int) to initialize h


public void seth(int y){
h = y;
}

//LINE-3: write the function area() to return area of rectangle


public int area(){
return w*h;
}
}
public class FClass{
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int w = Integer.parseInt(sc.nextLine());
int h = Integer.parseInt(sc.nextLine());
Rectangle r = new Rectangle();
r.setw(w);
r.seth(h);
int area = r.area();
System.out.print(area);
}
}

W02PPA2

Write a program to accept a string input from user and print the characters at even indices.

import java.util.*;
class FClass {

public static void main(String[] args){


Scanner sc = new Scanner(System.in);
String s1 = sc.next();
evenDisplay(s1);
}
//Define evenDisplay(String) method here
public static void evenDisplay(String s){
for(int i=0;i<s.length();i+=2)
System.out.print(s.charAt(i));
}

W03PPA1
Write a class named Calculator that has the following methods:
sum(double a, double b) that prints the value of a + b
subtraction(double a, double b) that prints the value of a - b
multiply(double a, double b) that prints the value of a * b
division(double a, double b) that prints the value of a / b

Write another class named UpdatedCalculator that inherits all the methods of Calculator and also has the following method:

remainder(double a, double b) that prints the value of a % b

import java.util.*;
class Calculator{
// Fill the code
public void sum(double a, double b){
System.out.println(a+b);
}
public void subtraction(double a, double b){
System.out.println(a-b);
}
public void multiply(double a, double b){
System.out.println(a*b);
}
public void division(double a, double b){
System.out.println(a/b);
}
}
class UpdatedCalculator extends Calculator{
// Fill the code
public void remainder(double a, double b){
System.out.println(a%b);
}
}
public class CalculatorCheck{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double n1 = sc.nextDouble();
double n2 = sc.nextDouble();
Calculator c = new Calculator();
c.sum(n1, n2);
c.subtraction(n1, n2);
c.multiply(n1, n2);
c.division(n1, n2);
UpdatedCalculator uc = new UpdatedCalculator();
uc.remainder(n1, n2);
}

W03PPA2

Consider the following Java program. Implement the code as instructed in the comment, such that it satisfies
the given test cases and is in coherence with the given main function.

import java.util.*;
class Point{
private int x, y;
// implement the constructor and
// override the toString() and equals() methods
Point(int x, int y)
{
this.x=x;
this.y=y;
}
public boolean equals(Point p)
{
if(x==p.x && y==p.y)
return true;
else
return false;
}
public String toString()
{
return "("+x+", "+y+")";
}

class FClass{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x1 = sc.nextInt();
int y1 = sc.nextInt();
int x2 = sc.nextInt();
int y2 = sc.nextInt();

Point p1 = new Point(x1, y1);


Point p2 = new Point(x2, y2);

if(p1.equals(p2))
System.out.println(p1 + "==" + p2);
else
System.out.println(p1 + "!=" + p2);
}
}

W04PPA1

Implement the code as instructed in the comments, such that it satisfies the given test cases.

import java.util.*;
interface Searchable{
public int search(int start_index, Object key);
}
class Char{
private char c;
public Char(char c_) {
c = c_;
}
public boolean equals(Object d) {
//implement equals() for Char
if(this==d) return true;
if (d == null || getClass() != d.getClass()) return false;
Char aChar = (Char) d;
return c == aChar.c;
}
}
class CharArray implements Searchable{
private Char[] carr;
public CharArray(Char[] carr_){
carr = carr_;
}
public int search(int start_index, Object key) {
//search the key in array carr from the index start_index
//if the key found, return index of the first occurrence of the key
//else return -1
for(int i=start_index;i<carr.length;i++)
{
if(this.carr[i].equals(key))
{
return i;
}
}
return -1;
}
}

class FrequencyCounter{
public static int getFrequency(Searchable ob, Object key){
if (ob instanceof CharArray) {
//count occurrences of the key in ob using search function
//count occurrences of the key in ob using search function
int num=0,i=0;
i = ob.search(i,key);
while(i>-1)
{
if(i!=-1)
{
num+=1;
}
i = ob.search(i+1,key);
}
return num;
}
else
return 0;
}
}
class FClass{
public static void main(String[] args) {
String str;
char c;
Scanner sc = new Scanner(System.in);
str = sc.nextLine();
c = sc.next().charAt(0);
Char key = new Char(c);
Char[] cA = new Char[str.length()];
for(int i = 0; i < str.length(); i++) {
cA[i] = new Char(str.charAt(i));
}
CharArray caObj = new CharArray(cA);
System.out.println(FrequencyCounter.getFrequency(caObj, key));
}
}

W04PPA2

Please follow the comments and given code segments to complete the program in accordance with the sample outputs.

Both the Voter and EVM classes must be created in such a way that they enforce the existence of only a
single instance at a time. Each Voter object must be mapped with a unique EVM object and vice versa.
A Voter must be allocated an EVM and then the voting process should start, once voting is completed
that particular EVM should be freed and the next voter should be called.
Again a new EVM must be allocated to the next voter like previously and the process continues till
all the voters cast their votes.

import java.util.Scanner;

class Voter{

// Define appropriate variables for implementing singleton behaviour


// in accordance with the given coded parts and sample output
static int current_voter_count = 0;
static int total_no_of_voters;
static Voter new_voter;

private Voter() {
current_voter_count++;
}

public static Voter getVoter() {


//implement singleton behaviour
if (new_voter == null) {
new_voter = new Voter();
return new_voter;}
else {
throw new NullPointerException();
}

public void firstVoter(){


if(new_voter != null) {
EVM new_machine = EVM.getEVM(new_voter);
new_machine.startVoting();
}
}

public void callNewVoter() {


// Write code to setup a new EVM object for the new voter
if (total_no_of_voters < current_voter_count + 1) {
return;
}
new_voter = null;
getVoter();
EVM new_machine = EVM.getEVM(new_voter);
//Ignore the following 6 lines of code
//but do not delete this code in your submission
//========================================================================
try {
EVM x = EVM.getEVM(null);
x.startVoting();
}catch(NullPointerException e) {
System.out.println("EVM is Singleton");
}
//========================================================================
// Resume writing your code here
new_machine.startVoting();

// Hint: Write code to start voting for the new user on the new EVM
}
}

class EVM{

// Define appropriate variables for implementing singleton behaviour


// in accordance with the given coded parts and sample output

static Voter current_voter;


static int evm_count = 0;
static EVM new_EVM;

private EVM(Voter v) {
current_voter = v;
evm_count++;
}
public static EVM getEVM(Voter v) {
// Implement singleton behaviour
if (v == null) {
throw new NullPointerException();
}
new_EVM = new EVM(v);
return new_EVM;
}
public void startVoting() {
// Complete voting for the current voter and call the next voter
// Hint : Use callback here
System.out.println("voting under process on EVM number " + evm_count);
System.out.println("Voting completed for voter " + (current_voter.current_voter_count));
current_voter.callNewVoter();

}
}

public class Election{


public static void main(String args[]) {
Scanner s = new Scanner(System.in);
Voter.total_no_of_voters = s.nextInt();
// Assume input is always non zero
Voter v = Voter.getVoter();

//Trying to create another voter when one voter is in the middle of


//voting process, students can ignore this try-catch block of code

try {
Voter x = Voter.getVoter();
x.callNewVoter();
} catch(NullPointerException e) {
System.out.println("Voter is Singleton");
}

//Starting the first vote of the day


v.firstVoter();
}
}

W05PPA2

Complete the Java code given below that takes as input a string array, where each string is assured
to be either an integer or a double in string format. Your code must segregate the two types -
integer and double - and print the double values followed by the integer values. For this, your code
must iterate through the input array, and add each element to the appropriate array based on its
type.

import java.lang.reflect.*;
import java.util.*;
class ClassStats{
public static int getPubMethodCount(String cname) {
try {
//add code to return the count of
//public methods in the given class
Class c = Class.forName(cname);
Method[] mA = c.getMethods();
return mA.length;
}catch(Exception e) { return -1; }
}
public static int getAllMethodCount(String cname) {
try {
//add code to return the count of all
//declared methods in the given class
Class c = Class.forName(cname);
Method[] mA = c.getDeclaredMethods();
return mA.length;
}catch(Exception e) { return -1; }
}
public static int getPubFieldCount(String cname) {
try {
//add code to return the count of
//public fields (instance variables) in the given class
Class c = Class.forName(cname);
Field[] mF = c.getFields();
return mF.length;
}catch(Exception e) { return -1; }
}
public static int getAllFieldCount(String cname) {
try {
//add code to return the count of
//all fields (instance variables) in the given class
Class c = Class.forName(cname);
Field[] mF = c.getDeclaredFields();
return mF.length;
}catch(Exception e) { return -1; }
}
public static int getPubContCount(String cname) {
try {
//add code to return the count of
//public constructors in the given class
Class c = Class.forName(cname);
Constructor[] mC = c.getConstructors();
return mC.length;
}catch(Exception e) { return -1; }
}
public static int getAllContCount(String cname) {
try {
//add code to return the count of
//all constructors in the given class
Class c = Class.forName(cname);
Constructor[] mC = c.getDeclaredConstructors();
return mC.length;
}catch(Exception e) { return -1; }
}
}

class FClass{
public static void main(String[] args) {
String cname;
Scanner sc = new Scanner(System.in);
cname = sc.nextLine();
System.out.println("Constructor: " +
ClassStats.getPubContCount(cname) + ", " +
ClassStats.getAllContCount(cname));
System.out.println("Fields: " +
ClassStats.getPubFieldCount(cname) + ", " +
ClassStats.getAllFieldCount(cname));
System.out.println("Methods: " +
ClassStats.getPubMethodCount(cname) + ", " +
ClassStats.getAllMethodCount(cname));
}
}

W06PPA1

Complete the Java code below that takes a Map object as input, and removes key-value pairs from the
object that satisfy the defined property.

The program should accept 6 key-value pairs, and add those to a Map object. Each key is the name of a
student and is of type String, whereas the corresponding value is the attendance of that student and is
of type Double. Assume that the student names are not repeated.

For each key-value pair, if the value satisfies the condition given in the property() method, then the
detained(Map<String, Double> obj) method should remove the key-value pair from the Map object.
After making all the updates, the detained(Map<String, Double> obj) method should invoke the
display(Map<String, Double> obj) method to print the names and the attendance of the students who
have not been removed from the Map object, in the format shown in the public test cases.

import java.util.*;
class RemoveStudent{
public boolean property(Double value) {
if(value<65)
return true;
return false;
}
public void detained(Map<String, Double> obj) {
// Define the detained() method}}
Collection<Double>values=obj.values();
Iterator<Double>it=values.iterator();
while(it.hasNext())
{
if(property(it.next()))
it.remove();
}
display(obj);
}
public void display(Map<String, Double> obj) {
System.out.println(obj);
}
}
public class Test {
public static void main(String[] args) {
Map<String,Double> map=new TreeMap<String,Double>();
Scanner scanner=new Scanner(System.in);
for (int i=0; i<6; i++) {
map.put(scanner.next(),scanner.nextDouble());
}
RemoveStudent obj=new RemoveStudent();
obj.detained(map);
}
}

W06PPA2

Complete the following program, which should work as a bank account validator and handle new account creation requests as detailed below.

The program should accept account opening requests in the following format:

Number of savings accounts to be opened

The account number acc_no and balance of each savings account

Number of current accounts to be opened

The account number, balance and over draft limit of each current account

All the requests are forwarded to the accountProcessor method which, in turn, validates the requests, and prints the details according to the
following criteria.

Each valid account should have a unique account number. In case there are multiple account requests with the same account number, only the
first request should be processed, and the rest should be discarded.

Hint: Use the LinkedHashSet collection, and override the equals and hashCode methods to achieve this feature. The methods equals and
hashCode are defined inside the Object class.

Once all the duplicate account requests are filtered out and unique valid accounts are opened, the program should print the details of all the
valid accounts in descending order of balance, in the format shown in the public test cases.

Hint: Use the TreeSet collection, and override the compareTo method to achieve this feature. The method compareTo is declared inside the
Comparable interface.
import java.util.*;
abstract class Account implements Comparable<Account>{
String acc_no;
double balance;
public Account(String no,double bal){
acc_no = no;
balance = bal;
}
//Override "compareTo" method here
public int compareTo(Account obj) {
if (obj.balance > this.balance) {
return 1;
}
else if (obj.balance < this.balance) {
return -1;
}
else {
return 1;
}
}

// Override "equals" method here


public boolean equals(Object o) {
Account obj = (Account)o;
return this.acc_no.equals(obj.acc_no);
}

// Override "hashCode" method here


public int hashCode() {
return Integer.parseInt(acc_no);
}
}
class SavingsAccount extends Account{
public SavingsAccount(String acc_no, double bal) {
// Complete the definition
super(acc_no, bal);
}
// Override the toString() method
public String toString() {
return "Savings Account:"+acc_no + " , Balance:"+balance;
}
}

class CurrentAccount extends Account{


double overdraft_limit;
public CurrentAccount(String acc_no, double bal, double odl) {
// Complete the constructor definition}}
super(acc_no, bal);
this.overdraft_limit = odl;
}

// Override the toString() method}}


public String toString() {
return "Current Account:"+acc_no + " , Balance:"+balance;
}
}

public class Test4 {


// Define the `accountProcessor' method here
public static void accountProcessor(ArrayList<Account> unprocessedAccounts) {
Set<Account> uniqueAccounts = new LinkedHashSet<Account>(unprocessedAccounts);
Set<Account> sortedAccounts = new TreeSet<Account>(uniqueAccounts);

for (Account a: sortedAccounts) {


System.out.println(a);
}
}

public static void main(String args[]) {


Scanner s = new Scanner(System.in);
ArrayList<Account> acc = new ArrayList<Account>();

//reading the number of savings accounts


int s_acc_count = s.nextInt();
for(int i=1;i<=s_acc_count;i++) {
//reading acc no
String no = s.next();
//reading balance
double bal = s.nextDouble();
acc.add(new SavingsAccount(no,bal));
}

//reading the number of current accounts


int c_acc_count = s.nextInt();
for(int i=1;i<=c_acc_count;i++) {
//reading acc no
String no = s.next();
//reading balance
double bal = s.nextDouble();
//reading overdraft limit
double lim = s.nextDouble();
acc.add(new CurrentAccount(no,bal,lim));
}

accountProcessor(acc);
}
}
W07PPA1

Complete the following program which models a car rental kiosk, and handles user requests as detailed below. The program

should first accept the number of car rental requests, and then accept details of each request in the following format. Total

number of passengers in the group for the rental request.

Destination of the visit.


These values are used for initialization of fields inside the constructor of CarRental class.

There is a HashMap called available_destinations which contains a set of preassigned destinations and the fare for dropping at that
destination. This map is also initialized in the constructor of CarRental class.

The carBooker() method processes the booking requests, and should have the following functionalities:

It should retrieve the fare for the chosen destination from the available_destinations map and calculate the fare per head by dividing the fare
for the destination by passenger_count. Then, it should print the destination and the fare per head, in the format shown in the public test cases.

The method should generate/handle the following exceptions.

ImproperHeadCountException should be thrown when passenger_count is zero or negative. The catch block handling this exception should
print the exception type along with the message: "Head count should be positive non-zero value".

If the chosen_destination is not found in available_destinations, a NullPointerException is thrown. The catch block handling this should create
a new exception called WrongDestinationException, set the new exception as the cause of the NullPointerException, and then re-throw it.
WrongDestinationException object should be created such that when getCause() is called, it prints the message as shown in the public test
cases.

import java.util.*;

//Define class WrongDestinationException


class WrongDestinationException extends Exception {
public WrongDestinationException(String message) {
super(message);
}
}
// Define class ImproperHeadCountException
class ImproperHeadCountException extends Exception {
public ImproperHeadCountException(String message) {
super(message);
}
}
class CarRental{
int passenger_count;
String chosen_destination;
HashMap<String,Double> available_destinations;

public CarRental(int pc, String dest) {


passenger_count = pc;
chosen_destination = dest;
//preassigned destinations and total car fare
//Leave the code below as it is
available_destinations = new HashMap<String,Double>();
available_destinations.put("Marina Beach", 2000.0);
available_destinations.put("Elliot's Beach", 5000.0);
available_destinations.put("Film City", 8000.0);
}

public void carBooker() throws WrongDestinationException, ImproperHeadCountException {


// define this method according to the problem description

if (passenger_count <= 0) {
System.out.println(new ImproperHeadCountException("Head count should be positive non zero value"));
} else {
try {
Double fare = available_destinations.get(chosen_destination);
System.out.println(
"Destination: " + chosen_destination + ", Head cost: " + (fare / passenger_count));
} catch (NullPointerException e) {
WrongDestinationException ex = new WrongDestinationException("Invalid destination");
e.initCause(ex);
throw e;
}
}
}

}
public class Test4{
public static void main(String args[]) {
Scanner s = new Scanner(System.in);

int num = s.nextInt(); //input the number of car rental requests


try {
for(int i=1;i<=num;i++) {
int heads = s.nextInt(); //enter head count
s.nextLine(); //enter destination
String dest = s.nextLine();
CarRental obj = new CarRental(heads,dest);
obj.carBooker();
}
}catch(Exception e) {
System.out.println(e.getCause());
}
}
}

W07PPA2

Write a Java program that accepts a string, an integer i and a character c as input. The character at position i in the given string has to be
replaced by the value of c. If the index is more than the length of the string, then it updates the last character of the given string with the value
of c. If the index i is negative, then it throws an appropriate error message. Implement the function replace such that it does the following:
It has three parameters - a character array (for the input string), an index and a character.

If the given index is in the range of the character array, it replaces the character at the given position; otherwise, catch
ArrayIndexOutOfBoundsException
In catch block (catchesArrayIndexOutOfBoundsException), if the index is beyond the length of the character array, it updates the last character
of the given character array.

If the index is negative, then it rethrows the exception to forward the exception to the caller function main

import java.util.*;
class FClass{

//implement function replace()


public static char[] replace(char[] arr, int i, char ch){
try {
arr[i] = ch;
return arr;
} catch (ArrayIndexOutOfBoundsException e){
if (i >= arr.length) {
arr[arr.length - 1] = ch;
return arr;
} else {
throw e;
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = sc.next();
int i = sc.nextInt();
char c = sc.next().charAt(0);
try {
String s2 = new String(replace(s1.toCharArray(), i, c));
System.out.println(s2);
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}
}

W08PPA1

Write a program to clone an object e1 of class Employee by implementing the interface Cloneable. After cloning, update the department and
the address of e1. Complete the program as detailed below to achieve this functionality.

Define classes Address and Department that implement the interface Cloneable, and have the following members:

In both classes, add an instance variable of String type (to store the address and the department respectively)

Implement the required constructor(s) and accessors.

Override the method clone.

Define a class Person that implements the interface Cloneable, and has the fol lowing members:

Instance variables name of type String and addr of type Address

Implement the required constructor(s) and accessors

Override the method clone

Define a class Employee that implements the interface Cloneable, extends the class Person, and has the following members:

Instance variable dept of type Department

Implement the required constructor(s) and accessors.

Override the method clone.

Define a method updateEmp to update the dept and addr of an Employee object
import java.util.*;
class Address implements Cloneable{
String ad;
Address(String a){
ad =a;
}
public String getad(){
return this.ad;
}
public Address clone() throws CloneNotSupportedException{
return (Address)super.clone();
}
}
//define class Address
class Department implements Cloneable{
String dep;
Department(String d){
dep =d;
}
public String getdep(){
return this.dep;
}
public Department clone() throws CloneNotSupportedException{
return (Department)super.clone();
}
}
//define class Department
class Person implements Cloneable{
String name;
Address addr;
Person(String n,Address a){
this.name = n;
this.addr = a;
}
public String getname(){
return this.name;
}
public Address getadd(){
return this.addr;
}
public Person clone() throws CloneNotSupportedException{
Person newp = (Person)super.clone();
Address newa = this.addr.clone();
newp.addr = newa;
return newp;
}
}
//define class Person
/*
Vinay Kota HR
Mumbai Finance

Vinay : Mumbai : Finance, Vinay : Kota : HR


*/
class Employee extends Person implements Cloneable{
Department dept;
Employee(String n, Address a, Department d){
super(n,a);
this.dept = d;
}
public Department getdep(){
return this.dept;
}
public void updateEmp(String a, String d){
this.addr = new Address(a);
this.dept = new Department(d);
}
public String toString(){
return name + " : " + addr.getad() + " : " + dept.getdep();
}
public Employee clone() throws CloneNotSupportedException{
Employee newe = (Employee)super.clone();
newe.dept = this.dept.clone();
return newe;
}
}
//define class Employee
public class FClass{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String n = sc.next(); //read name
String a1 = sc.next(); //read address
String d1 = sc.next(); //read department
String a2 = sc.next(); //read new address
String d2 = sc.next(); //read new department
try {
Employee e1 = new Employee(n, new Address(a1), new Department(d1));
Employee e2 = e1.clone();
e1.updateEmp(a2, d2);
System.out.println(e1 + ", " + e2);
}
catch(CloneNotSupportedException e) {
System.out.println("clone() not supported");
}
}
}

W08PPA2

A school is planning for a second Covid-19 vaccination drive on 30/03/2022, for students who have already taken the first dose. A student is
eligible for the second dose if 28 days have passed since the first dose. Write a Java program to find the list of students who are eligible for the
second dose of vaccination, based on the date of their first dose. Note that you must use the Stream class.

Your program takes as input a positive integer, which is the total number of students, followed by the roll number and the date of first dose of
vaccination in “dd/MM/yyyy” format for each student.

Your program should print the roll numbers of all students who are eligible for the second dose on 30/03/2022 The roll number, the date of

first dose of vaccination and the planned date of second dose are available as instance variables in class Student. Things to be done:

Define method isEligible() inside class Student that returns true if the student is eligible for the second dose. Define

class StudentList inside which you have to define two methods - getEligibleList(List) and isEmpty(Stream). The

method getEligibleList(List) returns a stream of eligible students using method isEligible() inside class Student

The method isEmpty(Stream) checks if the stream is empty, in order to customize the output message. If the stream is empty, it should print
the message: There are no eligible students. If the stream is not empty, then it prints the message: The list of eligible students are: followed by
the roll numbers of eligible students.

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

class Student{
private int roll_num;
private Date dose_one = new Date();
private Date dose_two = new Date();

public int getRollNo() {


return roll_num;
}
public Student(int roll_num, String dd_str) {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
this.roll_num = roll_num;
try {
dose_one = sdf.parse(dd_str);
dose_two = sdf.parse("30/03/2022");
}
catch(ParseException e){
System.out.println("Incorrect Date Format");
}
}
public boolean isEligible() {
//Complete the method definition
long t = 2419200000L;
long t1 = dose_one.getTime();
long t2 = dose_two.getTime();
if(t2-t1 > t){
return true;
}
return false;
}
}
/*
Define class StudentList inside which you have to define two methods - getEligibleList(List<Student>) and
isEmpty(Stream<Student>).
The method getEligibleList(List<Student>) returns a stream of eligible students using method isEligible()
inside class Student
The method isEmpty(Stream<Student>) checks if the stream is empty, in order to customize the output message.
If the stream is empty, it should print the message: There are no eligible students. If the stream is not
empty, then it prints the message:
The list of eligible students are: followed by the roll numbers of eligible students.

*/
class StudentList{
public Stream<Student> getEligibleList(List<Student> stul){
return stul.stream().filter(w -> w.isEligible());
}
public boolean isEmpty(Stream<Student> stustr){
if(stustr.count() == 0){
return true;
}
return false;
}

}
//Define class StudentList here.
//Inside class StudentList, define method getEligibleList(List<Student>)
//that uses the method isEligible() in class Student to return the
//stream of eligible students.

//Define method isEmpty(Stream<Student>)


//that helps customizing output message
public class SecondDose{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int roll_num;
String dose_one_str;
List<Student> full_list = new ArrayList<Student>();

int num = sc.nextInt(); //Number of students


for (int i=0; i<num; i++) {
roll_num = sc.nextInt(); //Roll Number
dose_one_str = sc.next(); //Date of Dose One
Student st = new Student(roll_num, dose_one_str);
full_list.add(st); // Add the student to an ArrayList
}
StudentList list = new StudentList();
Stream<Student> eligible_list = list.getEligibleList(full_list);
if (!list.isEmpty(eligible_list)) {
System.out.println("The list of eligible students are: ");
eligible_list = list.getEligibleList(full_list);
eligible_list.forEach(s -> System.out.println(s.getRollNo()));
}
else {
System.out.println("There are no eligible students.");
}
sc.close();
}
}

You might also like