Java PPA Solution - Colaboratory
Java PPA Solution - Colaboratory
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;
}
W02PPA2
Write a program to accept a string input from user and print the characters at even indices.
import java.util.*;
class FClass {
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:
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();
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{
private Voter() {
current_voter_count++;
}
// Hint: Write code to start voting for the new user on the new EVM
}
}
class 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();
}
}
try {
Voter x = Voter.getVoter();
x.callNewVoter();
} catch(NullPointerException e) {
System.out.println("Voter is Singleton");
}
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:
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;
}
}
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
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.
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.*;
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);
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{
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)
Define a class Person that implements the interface Cloneable, and has the fol lowing members:
Define a class Employee that implements the interface Cloneable, extends the class Person, and has the following members:
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
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();
*/
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.