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

Live Coding Java

Java

Uploaded by

Vivek Reddy
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)
19 views48 pages

Live Coding Java

Java

Uploaded by

Vivek Reddy
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/ 48

BSCCS2005: Sample Programming Assignment

with Test Cases and Solutions


1. Write the Java code as instructed.

• Class Faculty has the following members.


– String name, double salary as private instance variables
– Constructor to initialize the instance variables
– Method public double bonus(float percent) that returns the bonus com-
puted as (percent/100.0)*salary
– You should define method getDetails() to display name and salary of an
Faculty
– You should overload method getDetails() as getDetails(float percent)
to display the name, salary and bonus of an Faculty
• Class Hod extends class Faculty and has the following members.
– String personalAssistant as private instance variable
– Constructor to initialize the instance variables of Hod that includes the instance
variables of Faculty
– You should override method public double bonus(float percent) that re-
turns the bonus of a Hod as 50 percent less bonus than a regular faculty
– You should override method getDetails() to display the name, salary and
personalAssistant of Hod.
– You should override method getDetails(float percent) to display the name,
salary, personalAssistant and bonus of a Hod
• Class InheritanceTest has the main method and the following functionality.
– It creates objects of Faculty and Hod types, and also accepts the required input
values.
– Invokes methods getDetails() and getDetails(float percent) on Faculty
and Hod objects.

class Faculty{
private String name;
private double salary;
public Faculty(String name, double salary) {
this.name = name;
this.salary = salary;
}
public double bonus(float percent){
return (percent/100.0)*salary;
}

// Define method getDetails()


// Override method getDetails(float percent)

Page 2
}
class Hod extends Faculty{
private String personalAssistant;
public Hod(String name, double salary, String pa) {
super(name, salary);
this.personalAssistant = pa;
}

// Override method bonus(float percent)


// Override method getDetails()
// Override method getDetails(float percent)

}
public class InheritanceTest {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Faculty obj1 = new Faculty(sc.next(), sc.nextDouble());

Faculty obj2 = new Hod(sc.next(), sc.nextDouble(), sc.next());

System.out.println(obj1.getDetails());
System.out.println(obj1.getDetails(10));

System.out.println(obj2.getDetails());
System.out.println(obj2.getDetails(10));
}
}

Page 3
Public test case 1:
Input:

Srihari 50000
Vishnu 80000 laxmi

Output:

Srihari, 50000.0
Srihari, 50000.0, bonus = 5000.0
Vishnu, 80000.0, laxmi
Vishnu, 80000.0, laxmi, 4000.0

Public test case 2:


Input:

Mohan 45000
Manoj 78000 dhanush

Output:

Mohan, 45000.0
Mohan, 45000.0, bonus = 4500.0
Manoj, 78000.0, dhanush
Manoj, 78000.0, dhanush, 3900.0

Private test case 1:


Input:

Manjula 65000
Ganesh 87000 Harsha

Output:

Manjula, 65000.0
Manjula, 65000.0, bonus = 6500.0
Ganesh, 87000.0, Harsha
Ganesh, 87000.0, Harsha, 4350.0

Page 4
Solution:
class Faculty{
private String name;
private double salary;
public Faculty(String name, double salary) {
this.name = name;
this.salary = salary;
}
public double bonus(float percent){
return (percent/100.0)*salary;
}
public String getDetails() {
return name + ", " + salary;
}
public String getDetails(float percent ) {
return getDetails()+ ", bonus = "+bonus(percent);
}
}
class Hod extends Faculty{
private String personalAssistant;
public Hod(String name, double salary, String pa) {
super(name, salary);
this.personalAssistant = pa;
}
public double bonus(float percent){
return 0.5*super.bonus(percent);
}
public String getDetails() {
return super.getDetails()+", "+ personalAssistant;
}
public String getDetails(float percent ) {
return getDetails()+", "+bonus(percent);
}
}
public class InheritanceTest {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Faculty obj1 = new Faculty(sc.next(), sc.nextDouble());

Faculty obj2 = new Hod(sc.next(), sc.nextDouble(), sc.next());

System.out.println(obj1.getDetails());

Page 5
System.out.println(obj1.getDetails(10));

System.out.println(obj2.getDetails());
System.out.println(obj2.getDetails(10));
}
}

Page 6
2. Write a Java program as instructed.

• Abstract class UPIPayment has two abstract methods: abstract void payment()
and abstract void rewards()
• Class PhonePay extends class UPIPayment and has the following members.
– private int amount as private instance variable
– Constructor to initialize the instance variable
– You should override method public void payment() such that the overridden
method displays the message "Phone pay:Payment success:" and invokes
method rewards().
– You should override method public void rewards() as follows.
∗ If amount < 500, then display the message "Sorry no rewards".
∗ Else, if amount >= 500, then display the message "10 off on next mobile
rc".
• Class Paytm extends class UPIPayment and has the following members.
– private int amount as private instance variable
– Constructor to initialize the instance variable
– You should override method public void payment() such that the overridden
method displays the message "Paytm:Payment success:" and invokes method
rewards().
– You should override method public void rewards() as follows.
∗ If amount < 500, then display the message "Sorry no rewards".
∗ Else, if amount >= 500, then display message "10 off on next DTH rc".
• Class UPIUser has the following method.
– Method public void transferAndGetRewards(UPIPayment obj) that invokes
method payment() using obj.
• Class AbstractTest has the main method, and has the following functionality.
– Creates an object of UPIUser
– Takes two amounts a1 for PhonePay and a2 for Paytm
– Invokes method transferAndGetRewards() first by passing an object of PhonePay
with amount a1 as parameter, and then by passing an object of Paytm with
amount a2 as parameter.

abstract class UPIPayment{


abstract void payment();
abstract void rewards();
}
class PhonePay extends UPIPayment{
private int amount;
public PhonePay(int amount) {

Page 7
this.amount = amount;
}

// Oveeride method payment()


// Override method rewards()

}
class Paytm extends UPIPayment{
private int amount;
public Paytm(int amount) {
this.amount = amount;
}

// Oveeride method payment()


// Override method rewards()

}
class UPIUser{
public void transferAndGetRewards(UPIPayment obj) {
obj.payment();
}
}
public class AbstractTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a1 = sc.nextInt();
int a2 = sc.nextInt();
UPIUser u = new UPIUser();
u.transferAndGetRewards(new PhonePay(a1));
u.transferAndGetRewards(new Paytm(a2));
}
}

Page 8
Public test case 1:
Input:

450
1000

Output:

Phone pay:Payment success:


Sorry no rewards
Paytm:Payment success:
10 off on next DTH rc

Public test case 2:


Input:

5000
499

Output:

Phone pay:Payment success:


10 off on next mobile rc
Paytm:Payment success:
Sorry no rewards

Private test case 1:


Input:

100
100

Output:

Phone pay:Payment success:


Sorry no rewards
Paytm:Payment success:
Sorry no rewards

Page 9
Solution:
abstract class UPIPayment{
abstract void payment();
abstract void rewards();
}
class PhonePay extends UPIPayment{
private int amount;
public PhonePay(int amount) {
this.amount = amount;
}
public void payment() {
System.out.println("Phone pay:Payment success:");
rewards();
}
public void rewards() {
if(amount < 500)
System.out.println("Sorry no rewards");
else if(amount >= 500)
System.out.println("10 off on next mobile rc");
}
}
class Paytm extends UPIPayment{
private int amount;
public Paytm(int amount) {
this.amount = amount;
}
public void payment() {
System.out.println("Paytm:Payment success:");
rewards();
}
public void rewards() {
if(amount < 500)
System.out.println("Sorry no rewards");
else if(amount >= 500)
System.out.println("10 off on next DTH rc");
}
}
class UPIUser{
public void transferAndGetRewards(UPIPayment obj) {
obj.payment();
}
}

Page 10
public class AbstractTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a1 = sc.nextInt();
int a2 = sc.nextInt();
UPIUser u = new UPIUser();
u.transferAndGetRewards(new PhonePay(a1));
u.transferAndGetRewards(new Paytm(a2));
}
}

Page 11
3. Write Java code as instructed.

• Define an interface Appraisable that has the following members:


– Default method default void appraisal(Teacher t) that increments the
salary of an Employee by (stuPassPer/100)*5000.
– Abstract method public abstract void checkAndUpdateSalary()
• Define an interface SpecialAppraisable that extends Appraisable and has the
following members:
– Default method default void spAppraisal(Teacher t) that increments the
salary of an Employee by (stuPassPer/100)*10000.
• Class Teacher that implements the interface SpecialAppraisable and has the
following members:
– String name, double salary and private double stuPassPer as private in-
stance variables
– Constructor to initialize the instance variables
– Mutator method to update salary
– Accessor method to access salary
– Accessor method to access stuPassPer
– Override method toString() that returns name, salary and stuPassPer of
the Teacher as a single concatenated string (each separated by a single space)
– Overriding method public void checkAndUpdateSalary() that has the fol-
lowing functionality.
∗ If stuPassPer>=60 and stuPassPer<75 then invoke the appraisal() method
from Appraisable interface
∗ Else, if stuPassPer>=75 and stuPassPer<=100 then invoke thespAppraisal()
method from SpecialAppraisable interface
• Class InterfaceTest that has the following members:
– You should define method public static void printUpdatedTeachList(Teacher[]
tList) that has the following functionality
∗ Iterate over array tList and invoke method checkAndUpdateSalary() on
each Teacher object.
∗ Then, iterate over tList and display each Teacher object.
– main method has the following functionality
∗ Creates and initializes an array tArr of three Teacher objects
∗ Invokes method printUpdatedTeachList(Teacher[] tList) to print the
updated details of each Teacher after the appraisal is applied

Page 12
// Define interface Appraisable
// Define interface SpecialAppraisable

class Teacher implements SpecialAppraisable{


private String name;
private double salary;
private double stuPassPer;
public Teacher(String name, double salary, double stuPassPer) {
this.name = name;
this.salary = salary;
this.stuPassPer = stuPassPer;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public double getstuPassPer() {
return stuPassPer;
}
public String toString() {
return name + ", " + salary + ", " + stuPassPer;
}
public void checkAndUpdateSalary() {
if(stuPassPer >= 60 && stuPassPer < 75)
appraisal(this);
else if(stuPassPer >= 75 && stuPassPer <= 100)
spAppraisal(this);
}
}
public class InterfaceTest {

// Define method printUpdatedTeachList

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
Teacher tArr[] = new Teacher[3];
for (int i = 0; i < tArr.length; i++)
tArr[i] = new Teacher(sc.next(), sc.nextDouble(), sc.nextDouble());

InterfaceTest.printUpdatedTeachList(tArr);

Page 13
}
}

Page 14
Public test case 1:
Input:

Akshay 50000 64.5


Anasuya 60000 80.00
Abhaya 75000 70

Output:

Akshay, 53225.0, 64.5


Anasuya, 68000.0, 80.0
Abhaya, 78500.0, 70.0

Public test case 2:


Input:

Dharani 76000 96
Thanvi 56000 72
Thannya 90000 85

Output:

Dharani, 85600.0, 96.0


Thanvi, 59600.0, 72.0
Thannya, 98500.0, 85.0

Private test case 1:


Input:

Kavya 54000 59
Chaithanya 65000 55
Sravani 73000 53

Output:

Kavya, 54000.0, 59.0


Chaithanya, 65000.0, 55.0
Sravani, 73000.0, 53.0

Page 15
Solution:
interface Appraisable{
default void appraisal(Teacher t){
t.setSalary(t.getSalary()+(t.getstuPassPer()/100)*5000);
}
public abstract void checkAndUpdateSalary();
}
interface SpecialAppraisable extends Appraisable{
default void spAppraisal(Teacher t){
t.setSalary(t.getSalary()+(t.getstuPassPer()/100)*10000);
}
}
class Teacher implements SpecialAppraisable{
private String name;
private double salary;
private double stuPassPer;
public Teacher(String name, double salary, double stuPassPer) {
this.name = name;
this.salary = salary;
this.stuPassPer = stuPassPer;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public double getstuPassPer() {
return stuPassPer;
}
public String toString() {
return name + ", " + salary + ", " + stuPassPer;
}
public void checkAndUpdateSalary() {
if(stuPassPer >= 60 && stuPassPer < 75)
appraisal(this);
else if(stuPassPer >= 75 && stuPassPer <= 100)
spAppraisal(this);
}
}
public class InterfaceTest {
public static void printUpdatedTeachList(Teacher[] tList) {

Page 16
for (int i = 0; i < tList.length; i++)
tList[i].checkAndUpdateSalary();
for (int i = 0; i < tList.length; i++)
System.out.println(tList[i]);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Teacher tArr[] = new Teacher[3];
for (int i = 0; i < tArr.length; i++)
tArr[i] = new Teacher(sc.next(), sc.nextDouble(), sc.nextDouble());

InterfaceTest.printUpdatedTeachList(tArr);
}
}

Page 17
4. Write a Java program that accepts list of student objects and updates the regular fees,
based on the number of backlogs that each student has.

• An interface Generatable that has the following member:


– Abstract method abstract void feeGenerate(Student s)
• Class Student that has the following members:
– String name, double fee and int backlogs as private instance variable.
– Constructor to initialize the name and backlogs.
– Mutator method to update the fee
– Accessor method to access the backlogs
– Override method toString() that returns name, fee and backlogs of the
Student as a single concatenated string (each separated by comma(,))
• Class ExamBranch that has the following members:
– A private inner class Regular that implements the interface Generatable and
overrides method public void feeGenerate(Student s) that, in turn, ini-
tializes the regular student fee as 1500.
– A private inner class Supple that implements the interface Generatable and
overrides method public void feeGenerate(Student s) that, in turn, has
the following functionality.
∗ If the student backlogs == 1, then update the student fee to 2000.
∗ Else, if the student backlogs == 2, then update the student fee to 2500.
∗ Else, if the student backlogs >= 3, then update the student fee to 3500.
– You should define method getRegularFee() that returns an object of Regular
class.
– You should define method getSuppleFee() that returns an object of Supple
class.
• Class PrivateClassTest has the following members:
– You should define method public static Student[] getStudentsFee(Student
sList[]) that does the following:
∗ Iterates over array sList such that in each iteration, invoke method
feeGenerate(Student s) on each Student object from Regular class, if
student backlogs == 0. Else, invoke method feeGenerate(Student s)
on each Student object from Supple class.
– main method has the following functionality
∗ Creates and initializes an array sArr of three Student objects
∗ Invokes method getStudentsFee(sArr) to get the updated details of each
Student after the fee is updated
∗ Prints the updated list

Page 18
import java.util.Scanner;
interface Generatable{
abstract void feeGenerate(Student s);
}
class Student {
private String name;
private double fee;
private int backlogs;
public Student(String name, int backlogs) {
this.name = name;
this.backlogs = backlogs;
}
public void setFee(double fee) {
this.fee = fee;
}
public int getBacklogs() {
return backlogs;
}
public String toString() {
return name + ", " + fee + ", " + backlogs;
}
}
class ExamBranch{
private class Regular implements Generatable{
public void feeGenerate(Student s) {
s.setFee(1500.00);
}
}
private class Supple implements Generatable{
public void feeGenerate(Student s) {
if(s.getBacklogs() == 1)
s.setFee(1500 + 500);
else if(s.getBacklogs() == 2)
s.setFee(1500 + 1000);
else if(s.getBacklogs() >=3 )
s.setFee(1500 + 2000);
}
}

// Define method getRegularFee()


// Define method getSuppleFee()

Page 19
public class PrivateClassTest {

// Define method getStudentsFee()

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
Student[] sArr = new Student[3];
for (int i = 0; i < sArr.length; i++) {
sArr[i] = new Student(sc.next(), sc.nextInt());
}
sArr = PrivateClassTest.getStudentsFee(sArr);
for (int i = 0; i < sArr.length; i++) {
System.out.println(sArr[i]);
}
}
}

Page 20
Public test case 1:
Input:

Ananya 0
Acharya 4
Ashok 2

Output:

Ananya, 1500.0, 0
Acharya, 3500.0, 4
Ashok, 2500.0, 2

Public test case 2:


Input:

Sharath 1
Shekar 0
Shhin 0

Output:

Sharath, 2000.0, 1
Shekar, 1500.0, 0
Shhin, 1500.0, 0

Private test case 1:


Input:

Bharath 3
Bharani 4
Balaji 5

Output:

Bharath, 3500.0, 3
Bharani, 3500.0, 4
Balaji, 3500.0, 5

Page 21
Solution:
import java.util.Scanner;
interface Generatable{
abstract void feeGenerate(Student s);
}
class Student {
private String name;
private double fee;
private int backlogs;
public Student(String name, int backlogs) {
this.name = name;
this.backlogs = backlogs;
}
public void setFee(double fee) {
this.fee = fee;
}
public int getBacklogs() {
return backlogs;
}
public String toString() {
return name + ", " + fee + ", " + backlogs;
}
}
class ExamBranch{
private class Regular implements Generatable{
public void feeGenerate(Student s) {
s.setFee(1500.00);
}
}
private class Supple implements Generatable{
public void feeGenerate(Student s) {
if(s.getBacklogs() == 1)
s.setFee(1500 + 500);
else if(s.getBacklogs() == 2)
s.setFee(1500 + 1000);
else if(s.getBacklogs() >=3 )
s.setFee(1500 + 2000);
}
}
public Generatable getRegularFee() {
return new Regular();
}

Page 22
public Generatable getSuppleFee() {
return new Supple();
}
}
public class PrivateClassTest {
public static Student[] getStudentsFee(Student sList[]){
ExamBranch obj;
for (int i = 0; i < sList.length; i++) {
if(sList[i].getBacklogs()==0) {
obj=new ExamBranch();
obj.getRegularFee().feeGenerate(sList[i]);
}
else {
obj=new ExamBranch();
obj.getSuppleFee().feeGenerate(sList[i]);
}
}
return sList;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Student[] sArr = new Student[3];
for (int i = 0; i < sArr.length; i++) {
sArr[i] = new Student(sc.next(), sc.nextInt());
}
sArr = PrivateClassTest.getStudentsFee(sArr);
for (int i = 0; i < sArr.length; i++) {
System.out.println(sArr[i]);
}
}
}

Page 23
5. Write a program that, given two integers, two doubles as x and y coordinates of two
points p1(x1,y1) and p2(x2,y2) on a two-dimensional plane as input, finds the mid-
point p3(x3,y3) of the line segment formed by p1 and p2 using the formula:
x1 + x2 y1 + y2
x3 = and y3 =
2 2

Generic class Point has the following members.

• Instance variables x and y


• A constructor to initialize x and y
• A method mid(Point p) to return the mid-point of the line segment joining the
current point to p
• A method that overrides the method toString() in the Object class to format the
output

Class Test has the main method.

• The main method accepts the two input points. The first line of input will be two
integers of point p1. The second line of input will be two doubles of point p2. It
then invokes the method mid of one of the objects.

Sample input 1:

3 4
5 6

Output:

(4,5)

Sample input 2:

-3 4
-5 6

Output:

(-4,5)

import java.util.*;

//Add your code for Class Point here

Page 24
public class Test{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Point<Integer> p1 = new Point<Integer>(sc.nextInt(), sc.nextInt());
Point<Double> p2 = new Point<Double>(sc.nextDouble(), sc.nextDouble());
Point<Double> p3 = p1.mid(p2);
System.out.println(p3);
}
}

Public test case 1:

2 3
2.2 4.2

Output:

(2.1,3.6)

Public test case 2:

7 8
5 6

Output:

(6.0,7.0)

Private test case 1:

-3 2
-5 -6

Output:

(-4.0,-2.0)

Private test case 2:

5 3
3.2 5.2

Output:

(4.1,4.1)

Page 25
Solution:

import java.util.*;
class Point<T extends Number>{
T x, y;
public Point(T x, T y) {
this.x = x;
this.y = y;
}
public Point<Double> mid(Point<?> p){
Point<Double> pt = new Point<Double>(0.0, 0.0);
pt.x = (this.x.doubleValue() + p.x.doubleValue()) / 2;
pt.y = (this.y.doubleValue() + p.y.doubleValue()) / 2;
return pt;
}
public String toString() {
return "(" + x + "," + y + ")";
}
}

public class Test{


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Point<Integer> p1 = new Point<Integer>(sc.nextInt(),
sc.nextInt());
Point<Double> p2 = new Point<Double>(sc.nextDouble(),
sc.nextDouble());
Point<Double> p3 = p1.mid(p2);
System.out.println(p3);
}
}

Page 26
6. Write a Java program that takes as input 4 Customer objects and the list of Customer
objects with attributes customer name, and expense. The program computes the dis-
count amount payable to each customer (assuming discount rate is 5% of the expense
value, and is applicable for all customers having expense value >= 1000) and prints the
discount amount in the format given in sample input-output. For customers who are
not eligible for discount, it prints Nondiscountable expense. Complete the program
as specified below:
• Define a checked exception (extends Exception) DiscountException that returns
the string Nondiscountable expense if getMessage method of DiscountException
is called.
• Define class Customer, which should have the following members:
– Instance variables – name and expense
– final variable – discountrate is
– a suitable constructor to initialize the instance variables
– accessors getName() to obtain the value of name
– method checkDiscount() that computes the discount amount if the expense
is >= 1000; otherwise, throws DiscountException.
• Class ExceptionTest has the main method and the method displayCustomers.
In function displayCustomers, invokes the checkDiscount() on each customer
object.
Sample Input:

Mark 1200
Adam 100
Jose 1100
Raj 1900

Output:

Mark : 60.0
Adam : Nondiscountable expense
Jose : 55.0
Raj : 95.0

import java.util.*;

//define checked exception DiscountException

// define class Customer

public class ExceptionTest{


static void displayCustomers(LinkedList<Customer> cus){

Page 27
// iterate through cus and invoke checkDiscount() on each customer object

}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
var cus = new LinkedList<Customer>();
for(int i = 0; i < 4; i++){
cus.add(new Customer(sc.next(),sc.nextDouble()));
}
displayCustomers(cus);
}
}

Public test case 1:


Input:

Jack 700
Adam 100
Jose 1100
Raj 1900

Output:

Jack : Nondiscountable expense


Adam : Nondiscountable expense
Jose : 55.0
Raj : 95.0

Public test case 2:


Input:

Lata 900
Puja 1100
Vinita 1900
Sudha 130

Output:

Lata : Nondiscountable expense


Puja : 55.0
Vinita : 95.0
Sudha : Nondiscountable expense

Private test case 1:


Input:

Page 28
Anil 150
Nisha 700
Amrit 2500
Arun 800

Output:

Anil : Nondiscountable expense


Nisha : Nondiscountable expense
Amrit : 125.0
Arun : Nondiscountable expense

Private test case 2:


Input:

Sona 900
Raj 1900
Puja 1000
Vinita 1990

Output:

Sona : Nondiscountable expense


Raj : 95.0
Puja : 50.0
Vinita : 99.5

Page 29
Solution:
import java.util.*;
class DiscountException extends Exception{
DiscountException(){
super("Nondiscountable expense");
}
}
class Customer{
private String name;
private double expense;
final double discountrate = 0.05;
public Customer(String n, double e){
name = n;
expense = e;
}
public String getName(){
return name;
}
public double checkDiscount() throws DiscountException{
if(expense < 1000)
throw new DiscountException();
return expense * discountrate;
}
}
public class ExceptionTest{
static void displayCustomers(LinkedList<Customer> cus){
for(var c : cus){
System.out.print(c.getName() + " : ");
try{
System.out.println(c.checkDiscount());
}catch(DiscountException ex){
System.out.println(ex.getMessage());
}
}
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
var cus = new LinkedList<Customer>();
for(int i = 0; i < 4; i++){
cus.add(new Customer(sc.next(),sc.nextDouble()));
}
displayCustomers(cus);

Page 30
}
}

Page 31
7. Write a Java program that takes as input 4 Shop objects and the list of Shop objects
with attributes shop name, and number of items sold nsold. The program should add
each customer name as key and number of items as value to the map object. After
adding all objects to the map, display the shop name which has sold maximum number
of items as shown in the test cases. Complete the program as specified below:

• Class Shop that has the following members:


– String name, int nsold as private instance variable
– Constructor to initialize the name and nsold
– Accessor methods to all instance variables
• Class MapTest has the following members:
– You should define method public static void printShopName(ArrayList<Shop>
sList) that does the following:
∗ Iterates over array sList such that in each iteration, add each customer
name as key and number of items as value to the map object.
∗ Print the shop name which has sold maximum number of items.
– main method has the following functionality
∗ Creates a list of 4 Shop objects.
∗ Invokes method printShopName(list) to print the shop name which has
sold maximum number of items.

Sample Input:

Orion 45
Ambience 115
Orion 45
Orion 10

Output:

Ambience : 115

import java.util.*;

import java.util.*;
class Shop{
private String name;
private int nsold;
public Shop(String s, int ns){
this.name = s;
this.nsold = ns;
}

Page 32
public String getName(){
return name;
}
public int getItemSold(){
return nsold;
}
}
public class MapTest {
public static void printShopName(ArrayList<Shop> sList) {
Map<String, Integer> m = new LinkedHashMap<String, Integer>();
String shop = "";
int sold = 0;

// iterate through sList and add each shop object to map ”m”

System.out.println(shop+" : "+sold);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Shop> list = new ArrayList<Shop>();
for (int i = 0; i < 4; i++) {
list.add(new Shop(sc.next(), sc.nextInt()));
}
printShopName(list);
}
}

Public test case 1:


Input:

SuperBazar 30
More 40
Shopsy 30
More 30

Output:

More : 70

Public test case 2:


Input:

Lulu 40
Lulu 34
DLF 54
DLF 67

Page 33
Output:

DLF : 121

Private test case 1:


Input:

HiLITE 56
Sarath-City 40
Z-Square 54
World-Trade 43

Output:

HiLITE : 56

Private test case 2:


Input:

Mantri-Square 56
Mantri-Square 76
Mantri-Square 11
Phoenix 590

Output:

Phoenix : 590

Page 34
Solution:

import java.util.*;
class Shop{
private String name;
private int nsold;
public Shop(String s, int ns){
this.name = s;
this.nsold = ns;
}
public String getName(){
return name;
}
public int getItemSold(){
return nsold;
}
}
public class MapTest {
public static void printShopName(ArrayList<Shop> sList) {
Map<String, Integer> m = new LinkedHashMap<String, Integer>();
String shop = "";
int sold = 0;
for(Shop s: sList)
m.put(s.getName(), m.getOrDefault(s.getName(),0)+s.getItemSold());
for (HashMap.Entry<String, Integer> entry : m.entrySet()){
if(entry.getValue()> sold) {
shop = entry.getKey();
sold = entry.getValue();
}
}
System.out.println(shop+" : "+sold);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Shop> list = new ArrayList<Shop>();
for (int i = 0; i < 4; i++) {
list.add(new Shop(sc.next(), sc.nextInt()));
}
printShopName(list);
}
}

Page 35
8. Complete the Java code below that takes a list of student objects as input, and removes
students from the list that satisfy the defined property.
Complete the program as specified below:

• Class Student that has the following members:


– String name, double attendance as instance variable
– Constructor to initialize the name and attendance
– Override method toString() that returns name and attendance of the Student
as a single concatenated string (each separated by a single space)
• Class RemoveStudent that has the following members:
– Method public boolean property(double value), it returns true if value<65
otherwise return false.
– You should define method public void detained(ArrayList<Student> sList)
that has the following functionality.
∗ It iterates through the list object and invokes property(double value)
on each student object.
∗ If any student satisfies the condition given in the property() method, then
remove the student object from the list, otherwise display the student
object.
• Class IteratorTest has the following members:
– main method has the following functionality
∗ Creates a list of 6 Student objects
∗ Invokes method detained(list) from RemoveStudent class

import java.util.*;
class Student{
String name;
double attendance;
public Student(String name, double attendance) {
this.name = name;
this.attendance = attendance;
}
public String toString() {
return name + ", " + attendance;
}
}
class RemoveStudent{
public boolean property(double value) {
if(value<65)
return true;
return false;

Page 36
}
public void detained(ArrayList<Student> sList) {

// Define the detained() method

}
}
public class IteratorTest {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
ArrayList<Student> list = new ArrayList<Student>();
for (int i=0; i<6; i++) {
list.add(new Student(scanner.next(),scanner.nextDouble()));
}
RemoveStudent obj=new RemoveStudent();
obj.detained(list);
}
}

Public test case 1:


Input:

virat 23.0
johny 78.9
suchith 56.9
juhee 45.00
karthik 90.0
shannu 67.0

Output:

johny, 78.9
karthik, 90.0
shannu, 67.0

Public test case 2:


Input:

Nani 34.0
Bala 89.0
Chiru 70.0
Venky 56.0
Nag 97.0
Raj 52.0

Page 37
Output:

Bala, 89.0
Chiru, 70.0
Nag, 97.0

Private test case 1:


Input:

Devi 56.0
Anup 64.0
Thaman 34.0
Thamiza 44.0
Choutha 55.0
Yuvan 69.0

Output:

Yuvan, 69.0

Page 38
Solution:
import java.util.*;
class Student{
String name;
double attendance;
public Student(String name, double attendance) {
this.name = name;
this.attendance = attendance;
}
public String toString() {
return name + ", " + attendance;
}
}
class RemoveStudent{
public boolean property(double value) {
if(value<65)
return true;
return false;
}
public void detained(ArrayList<Student> sList) {
Student obj;
Iterator<Student> it = sList.iterator();
while (it.hasNext()) {
obj = it.next();
if(property(obj.attendance))
it.remove();
else
System.out.println(obj);
}
}
}
public class IteratorTest {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
ArrayList<Student> list = new ArrayList<Student>();
for (int i=0; i<6; i++) {
list.add(new Student(scanner.next(),scanner.nextDouble()));
}
RemoveStudent obj=new RemoveStudent();
obj.detained(list);
}
}

Page 39
9. Write the java program that creates 3 objects of students and prints the name of student
with highest total. Implement the code as follows:
Define class Student with following members:

• String name, double[] marks (array length is 3) as instance variables which rep-
resents the name and marks of student
• Constructor to initialize instance variables
• Accessor method getName() that returns the name of student
• Method findTotal( ) that returns the total marks of the student

Define class Test that has the following members:

• Method getMax() which takes Student[] as parameter and returns the name of
the student with highest total.
• main() method, that creates 3 instances of Student, stores them in an array and
invokes the method getMax() by passing that Student[]

import java.util.*;

//Add your code for Class Student here

public class Test{


// Define the method getMax() here
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Student[] arr = new Student[3];
for(int i = 0; i < 3; i++){
String name = sc.next();
double[] m = {sc.nextDouble(), sc.nextDouble(), sc.nextDouble()};
arr[i] = new Student(name, m);
}
System.out.println(getMax(arr));
}
}

Public test case 1:

ram 67 78 90
latha 72 79 89
sonu 77 92 45

Output:

latha

Page 40
Public test case 2:

rahul 23 45 67
divya 34 48 69
rohit 45 51 78

Output:

rohit

Private test case 1:

s1 34.5 56.7 68
s2 45.4 66 78
s3 73 45.4 56

Output:

s2

Private test case 2:

s2 38.5 56.7 90
s1 45.4 66 78
s3 73 45.4 56

Output:

s1

Solution:

import java.util.*;
class Student {
private String name;
private double marks [];‘
public Student(String name, double[] marks) {
this.name = name;
this.marks = marks;
}
public String getName() {
return (this.name);

Page 41
}
public double findTotal() {
double total = 0.0;
for (double i : this.marks) {
total = total + i;
}
return (total);
}
}
class Test {
public static String getMax(Student[] student) {
double max_marks = 0.0;
String max_student = "";
for (Student i : student) {
double total_marks = i.findTotal();
if (total_marks > max_marks) {
max_student = i.getName();
max_marks = total_marks;
}
}
return max_student;
}
public static void main(String[] args) {
Student[] arr = new Student[3];
Scanner sc = new Scanner(System.in);
for(int i = 0; i < 3; i++){
String name = sc.next();
double[] m = {sc.nextDouble(), sc.nextDouble(), sc.nextDouble()};
arr[i] = new Student(name, m);
}
System.out.println(getMax(arr));
}
}

Page 42
10. Employee e1 does a set of projects. Employee e2 also does all the projects did by e1
except the first project, in place of which e2 does another project. Write a program that
defines two classes Employee and Test. Define copy constructor to create e2 from e1 in
such a way that changing the values of instance variables of either e2 or e1 should not
affect the other one. The code takes name of e2 and new project done by e2 as input.
Complete the program as specified below.

• Class Employee that has the following members.


– Private instance variables String name and String[] projects to store name
and projects respectively
– Define required constructor(s)
– Accessor methods getName( ) and getProject( ) to get name of employee
and project at specific index.
– Mutator methods setName( ) and setProject( ) to set name of employee
and project at specific index.
• Class Test that has the method main which does the following.
– Two objects of Employee e1 and e2 are created. e2 is created using e1
– name of e2 and second item bought by c2 are updated by taking the input
– name of e1, e2 and first project done by e1 and e2 are printed

Test Cases

Public test case 1 (Input):

Sneha PJ5

Output:

Surya: PJ1
Sneha: PJ5

Test Cases

Public test case 2 (Input):

Rohan PJ7

Output:

Surya: PJ1
Rohan: PJ7

Page 43
Private test case 1 (Input):

Megha PJ4

Output:

Surya: PJ1
Megha: PJ4

Private test case 2 (Input):

Srija PJ0

Output:

Surya: PJ1
Srija: PJ0

Template Code

import java.util.*;
class Employee{
String name;
String[] projects;
//***** Define constructor(s) here
public void setName(String n) {
name = n;
}
public void setProject(int index, String proj) {
projects[index] = proj;
}
public String getName() {
return name;
}
public String getProject(int indx) {
return projects[indx];
}
}
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] proj = {"PJ1", "PJ2", "PJ3"};
Employee e1 = new Employee("Surya", proj);
Employee e2 = new Employee(e1);

Page 44
e2.setName(sc.next());
e2.setProject(0, sc.next());
System.out.println(e1.getName() + ": " + e1.getProject(0));
System.out.println(e2.getName() + ": " + e2.getItem(0));
}
}

Solution:

import java.util.*;
class Employee{
String name;
String[] projects;
public Employee(String n, String[] proj){
name = n;
projects = proj;
}
public Employee(Employee e){
this.name = e.name;
int l = e.projects.length;
this.projects = new String[l];
for(int i = 0; i < l; i++){
this.projects[i] = c.projects[i];
}
}
public void setName(String n) {
name = n;
}
public void setProject(int index, String proj) {
projects[index] = proj;
}
public String getName() {
return name;
}
public String getProject(int indx) {
return projects[indx];
}
}
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] proj = {"PJ1", "PJ2", "PJ3"};

Page 45
Employee e1 = new Employee("Surya", proj);
Employee e2 = new Employee(e1);
e2.setName(sc.next());
e2.setProject(0, sc.next());
System.out.println(e1.getName() + ": " + e1.getProject(0));
System.out.println(e2.getName() + ": " + e2.getItem(0));
}
}

Page 46
11. Employee e1 does a set of projects. Employee e2 also does all the projects did by e1
except the first project, in place of which e2 does another project. Write a program that
defines two classes Employee and Test. Create copy of e1, say it as e2 in such a way
that changing the values of instance variables of either e2 or e1 should not affect the
other one. The code takes name of e2 and new project done by e2 as input. Complete
the program as specified below.

• Class Employee that implements Cloneable interface and has the following mem-
bers:
– Private instance variables String name and String[] projects to store name and
projects respectively
– Define required constructor
– Define accessor methods getName( ) and getProject( ) to get name of em-
ployee and project at specific index.
– Define mutator methods setName( ) and setProject( ) to set name of em-
ployee and project at specific index.
– Override the method clone( )
• Class Test that has the method main which does the following:
– Two objects of Employee e1 and e2 are created. e2 is created using e1.clone()
– Input to update name of e2 and second item bought by e2 are taken Names
of e1, e2 and first project done by e1 and e2 are printed.

Template Code

// Define class Employee here


public class Test {
public static void main(String[] args) throws CloneNotSupportedException{
Scanner sc = new Scanner(System.in);
String[] proj = {"PJ1", "PJ2", "PJ3"};
Employee e1 = new Employee("Surya", proj);
Employee e2 = e1.clone();
e2.setName(sc.next());
e2.setProject(0, sc.next());
System.out.println(e1.getName() + ": " + e1.getProject(0));
System.out.println(e2.getName() + ": " + e2.getProject(0));
}
}

Solution:

Page 47
import java.util.*;
class Employee implements Cloneable{
String name;
String[] projects;
public Employee(String n, String[] proj){
name = n;
projects = proj;
}
public void setName(String n) {
name = n;
}
public void setProject(int index, String proj) {
projects[index] = proj;
}
public String getName() {
return name;
}
public String getProject(int indx) {
return projects[indx];
}
public Employee clone() throws CloneNotSupportedException{
Employee e = (Employee)super.clone();
e.projects = e.projects.clone();
return e;
}
}
public class Test {
public static void main(String[] args) throws CloneNotSupportedException{
Scanner sc = new Scanner(System.in);
String[] proj = {"PJ1", "PJ2", "PJ3"};
Employee e1 = new Employee("Surya", proj);
Employee e2 = e1.clone();
e2.setName(sc.next());
e2.setProject(0, sc.next());
System.out.println(e1.getName() + ": " + e1.getProject(0));
System.out.println(e2.getName() + ": " + e2.getProject(0));
}
}

Page 48

You might also like