0% found this document useful (0 votes)
13 views97 pages

Java All Assignment

The document contains Java code for various assignments over several days, including a cafe billing system, a calculator, a 2D point class, and a fruit management system. It also includes a banking application with account management features. Each section demonstrates different programming concepts such as classes, inheritance, and user interaction through console input.

Uploaded by

sumitpatait2001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views97 pages

Java All Assignment

The document contains Java code for various assignments over several days, including a cafe billing system, a calculator, a 2D point class, and a fruit management system. It also includes a banking application with account management features. Each section demonstrates different programming concepts such as classes, inheritance, and user interaction through console input.

Uploaded by

sumitpatait2001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 97

Day 1:

Name – Sumit Patait


Roll No. 098
package day1_Assignment;

import java.util.*;
class Menu{
public static void main(String [] args){
Scanner sc=new Scanner(System.in);
double bill=0;
boolean exit=false;
int qty=0;
System.out.println("Welcome to cafe");
while(!exit){

System.out.println("1.Dosa:50");
System.out.println("2.Idli:30");
System.out.println("3.Samosa:20");
System.out.println("4.Kachori:20");
System.out.println("5.Dhokla:25");
System.out.println("0.Total bill");
switch(sc.nextInt()){
case 1:
System.out.println("enter the quantity");
qty=sc.nextInt();
bill+=qty*50;
break;
case 2:
System.out.println("enter the quantity");
qty=sc.nextInt();
bill+=qty*30;
break;
case 3:
System.out.println("enter the quantity");
qty=sc.nextInt();
bill+=qty*20;
break;
case 4:
System.out.println("enter the quantity");
qty=sc.nextInt();
bill+=qty*20;
break;
case 5:
System.out.println("enter the quantity");
qty=sc.nextInt();
bill+=qty*25;
break;
case 0:
System.out.println("Your total bill = "+bill);
exit=true;
break;
default:
System.out.println("Invalid choice!");
exit=true;

}
}
sc.close();
}
}
Calculator
package day1_Assignment;

import java.util.*;
class Calculator{
public static void main(String [] args){
Scanner sc=new Scanner(System.in);

boolean exit=false;

System.out.println("Welcome to Calculator");
System.out.println("enter two number");
int n1=sc.nextInt();
int n2=sc.nextInt();
while(!exit){

System.out.println("1.Add");
System.out.println("2.Subtract");
System.out.println("3.Multiply");
System.out.println("4.Divide");
System.out.println("5.Exit");
switch(sc.nextInt()){
case 1:
System.out.println("Addition : "+(n1+n2));
break;
case 2:
System.out.println("Subtraction : "+(n1-n2));
break;
case 3:
System.out.println("Multiplication : "+(n1*n2));
break;
case 4:
System.out.println("Division : "+(n1/n2));
break;
case 5:
System.out.println("Exiting...........");
exit=true;
break;
default:
System.out.println("Invalid choice!");
exit=true;
}
}
sc.close();
}
}
Day 2:
Class
package day2_assignment;

class Point2D{
private int x;
private int y;
Point2D(int x,int y){
this.x=x;
this.y=y;
}
String show(){
return "cordinates : x = "+x+" , y = "+y;
}
boolean isEqual(Point2D p1){
if(this.x==p1.x && this.y==p1.y) return true;
else return false;
}
double calculate(Point2D p){
return Math.sqrt(Math.pow(((p.x)-(this.x)),2)+Math.pow(((p.y)-(this.y)),2));
}

Tester :
package day2_assignment;

import java.util.Scanner;

public class Test2D {


public static void main(String [] args){
Scanner sc= new Scanner(System.in);
System.out.println("Enter the two cordinates points for 1 obj");
Point2D p1=new Point2D(sc.nextInt(),sc.nextInt());
System.out.println("Enter the two cordinates points for 2 obj");
Point2D p2=new Point2D(sc.nextInt(),sc.nextInt());

System.out.println("p1 : "+p1.show());
System.out.println("p2 : "+p2.show());

if(p1.isEqual(p2)){
System.out.println("cordinates of p1 and p2 is same");
}
else{
System.out.println("cordinates of p1 and p2 is different");
System.out.println("Distance between two point are : "+p1.calculate(p2));
}

sc.close();

}
}
Day 3:
Java Class:
package com.cdac.core;

public class Point2D {

private int x;
private int y;

public Point2D(int x, int y) {


this.x = x;
this.y = y;
}

public String show() {


return "cordinates : x = " + x + " , y = " + y;
}

public boolean isEqual(Point2D p1) {


if (this.x == p1.x && this.y == p1.y)
return true;
else
return false;
}

public double calculate(Point2D p) {


return Math.sqrt(Math.pow(((p.x) - (this.x)), 2) + Math.pow(((p.y) - (this.y)), 2));
}
public Point2D addoffset(int x,int y) {
return new Point2D (this.x+x,this.y+y);
}

Tester :
package com.cdac.tester;

import java.util.Scanner;

import com.cdac.core.Point2D;

public class Test2D {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the two cordinates points for 1 obj");
Point2D p1 = new Point2D(sc.nextInt(), sc.nextInt());
System.out.println("Enter the two cordinates points for 2 obj");
Point2D p2 = new Point2D(sc.nextInt(), sc.nextInt());

System.out.println("p1 : " + p1.show());


System.out.println("p2 : " + p2.show());

if (p1.isEqual(p2)) {
System.out.println("cordinates of p1 and p2 is same");
} else {
System.out.println("cordinates of p1 and p2 is different");
System.out.println("Distance between two point are : " + p1.calculate(p2));
}
System.out.println("enter the offset for new Points");
Point2D newpoint=p1.addoffset(sc.nextInt(), sc.nextInt());
System.out.println("New Points : " + newpoint.show());

sc.close();

}
Test Menu
package com.cdac.tester;

import java.util.Scanner;

import com.cdac.core.Point2D;

public class TestMenu {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.println("Enter the number points you want to plot...?");
Point2D p[]=new Point2D[sc.nextInt()];
int choice=-1;
do {
System.out.println("1.plot a point");
System.out.println("2.Display points");
System.out.println("0.Exit");
System.out.println("Enter your choice");
choice= sc.nextInt();
switch (choice) {
case 1:
System.out.println("enter the index");
int index=sc.nextInt();
if(index<p.length && p[index]==null ) {
System.out.println("enter the x and y cordinates for
"+index+"point");
p[index]=new Point2D(sc.nextInt(), sc.nextInt());

}
else {
System.out.println("Invalid index!!!");
}
break;
case 2:
System.out.println("Points Details!!");
for(Point2D a:p) {
System.out.println(a.show());
}
break;
case 0:
System.out.println("Exiting......");
break;

default:
System.out.println("Invalid Choice!!!!");
}
}while(choice!=0);
}

}
Day 4:
Fruit class
package com.app.fruits;

public abstract class Fruit {


private String color;
private double weight;
private String name;
private boolean isFresh=true;

public Fruit (String color,double weight,String name) {


this.color=color;
this.weight=weight;
this.name=name;

}
@Override
public String toString() {
return "Fruit :----"+" color: "+color+ " ,weight: "+weight+" ,name:
"+name+" ,isFresh :"+isFresh;

}
public abstract String taste();

public String getName() {


return name;
}
public void setStale() {
isFresh=false;
}

Apple :
package com.app.fruits;

public class Apple extends Fruit {


public Apple(String color,double weight,String name) {
super(color,weight,name);
}
@Override
public String taste() {
return "sweet n sour";
}
public void jam() {
System.out.println(getName()+" Apple making jam !");
}
}

Orange class:
package com.app.fruits;

public class Orange extends Fruit {


public Orange(String color,double weight,String name) {
super(color,weight,name);
}
@Override
public String taste() {
return "sour";
}
public void juice() {
System.out.println(getName()+ " Orange Extracting juice !");
}

Mango class:
package com.app.fruits;

public class Mango extends Fruit {


public Mango(String color,double weight,String name) {
super(color,weight,name);
}
@Override
public String taste() {
return "sweet";
}
}

Alphonso class:
package com.app.fruits;

public class Alphonso extends Mango{


public Alphonso(String color,double weight,String name) {
super(color,weight,name);
}
@Override
public String taste() {
return "Extremely Sweet !";
}
public void pulp() {
System.out.println(getName()+" Alphonso Creating pulp !");
}
}

Tester:
package com.app.tester;
import java.util.Scanner;

import com.app.fruits.*;
public class FruitBasket {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.println("enter the Basket size");
Fruit basket[]=new Fruit[sc.nextInt()];
boolean exit= false;
boolean flag=false;
int index=0;
while(!exit) {
System.out.println("option for Fruit basket \n"+"1. Add Alphonso\n"
+ "2. Add Orange\n"
+ "3. Add Apple\n"+"4. Display names of all fruits in the
basket\n"
+"5.Display name,color,weight , taste of all fresh fruits , in
the basket.\n"
+"6.Invoke fruit specific functionality (pulp / juice / jam)\n"+
"7.Mark a fruit in a basket , as stale\n"+
"8.Mark all sour fruits stale\n "
+"0.Exit");
System.out.println("enter your choice");
switch (sc.nextInt()) {
case 1:

if(index<basket.length) {
System.out.println(" enter the details of Alphanso - color
weight name ");
basket[index]=new
Alphonso(sc.next(),sc.nextDouble(),sc.next());
index++;
}
else System.out.println("Basket is Full ! ");
break;
case 2:
if(index<basket.length) {
System.out.println(" enter the details of Orange - color
weight name " );
basket[index]=new
Orange(sc.next(),sc.nextDouble(),sc.next());
index++;
}
else System.out.println("Basket is Full ! ");
break;
case 3:

if(index<basket.length) {
System.out.println(" enter the details of Apple - color
weight name");
basket[index]=new
Apple(sc.next(),sc.nextDouble(),sc.next());
index++;
}
else System.out.println("Basket is Full ! ");
break;
case 4:
System.out.println("Baskte Fruits:");
for(Fruit f:basket) {
if(f!=null) {
System.out.println(f.getName());
flag=true;
}
}
if(!flag) System.out.println("Basket is empty!!!!");
break;
case 5:
System.out.println("All details of fruits");
for(Fruit f:basket) {
if(f!=null) {
System.out.println(f);
System.out.println("taste of fruit : "+f.taste());
flag=true;
}
}
if(!flag) System.out.println("Basket is empty!!!!");

break;
case 6:
System.out.println("Enter the basket index");
int i=sc.nextInt()-1;

if(i>=0 && i< index) {


Fruit f= basket[i];
if(f instanceof Apple) {
((Apple)f).jam();
}
else if(f instanceof Orange) {
((Orange)f).juice();
}
else {
((Alphonso)f).pulp();
}
}
else System.out.println("Invalid index !");
break;
case 7:
System.out.println("Enter the basket index");
i=sc.nextInt()-1;
if(i>=0 && i< index) {
Fruit f= basket[i];
f.setStale();
System.out.println("operration succesfull!!!!");
}
else System.out.println("Invalid index !");
break;
case 8:

for(Fruit f:basket) {
if(f!=null) {
if("sour".equals(f.taste())){
f.setStale();
System.out.println("operration succesfull!!!!");
}
}
else {
System.out.println("Basket is empty!!!!");
}
}
break;

case 0:
System.out.println("Exiting.....................");
exit=true;

}
}
sc.close();
}

}
Day 6:
BankAccount class
package com.app.bank;

public class BankAccount {


private int accountNo;
private String fisrtName;
private String lastName;
private double balance;
private String accType;
static int count = 100;

public BankAccount(String fisrtName, String lastName, double balance, String accType)


{
count++;
this.accountNo = count;
this.fisrtName = fisrtName;
this.lastName = lastName;
this.balance = balance;
this.accType = accType;
}

@Override
public String toString() {
return "BankAccount [accountNo=" + accountNo + ", fisrtName=" + fisrtName + ",
lastName=" + lastName
+ ", balance=" + balance + ", accType=" + accType + "]";
}

public void setBalance(double balance) {


this.balance = this.balance + balance;
}

public int getAccount() {


return accountNo;
}
}

BankingOperation:

package com.app.bank;

public interface BankingOperation {


BankAccount addAccount(String fisrtName, String lastName, double balance, String
accType);

void diplayAcc(BankAccount b);

void depositFund(BankAccount b, double balance);


}

Implementation :
package com.app.bank;

public class BankingOperationImpl implements BankingOperation {

@Override
public BankAccount addAccount(String fisrtName, String lastName, double balance,
String accType) {

return new BankAccount(fisrtName, lastName, balance, accType);


}

@Override
public void diplayAcc(BankAccount b) {
System.out.println(b);

@Override
public void depositFund(BankAccount b, double balance) {
b.setBalance(balance);

Tester :
package com.app.test;

import java.util.Scanner;

import com.app.bank.BankAccount;
import com.app.bank.BankingOperationImpl;

public class Test {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the bank size");
BankAccount accounts[] = new BankAccount[scanner.nextInt()];
boolean exit = false;
int index = 0;
BankingOperationImpl b1=new BankingOperationImpl();
while (!exit) {
System.out.println("Bank Options!!\n" + "1. Open bank account\n" + "2.
Display all accounts\n"
+ "3. Deposit Funds\n" + "0.Exit");
System.out.println("Enter your choice");
switch (scanner.nextInt()) {
case 1:
System.out.println("Enter your details -
firstname,lastname,balance,account type");
accounts[index+
+]=b1.addAccount(scanner.next(),scanner.next(),scanner.nextDouble(),scanner.next());
break;
case 2:
System.out.println("All accounts details!!!!");
for(BankAccount b:accounts) {
if(b!=null)
b1.diplayAcc(b);
}
break;

case 3:
System.out.println("Enter the account number and fund");
int aNo=scanner.nextInt();
double bal=scanner.nextDouble();
for(BankAccount b: accounts) {
if(b.getAccount()==aNo) {
b1.depositFund(b, bal);
}
}
break;
case 0:
System.out.println("Exiting..........");
exit=true;
break;
}
}
scanner.close();

Day 7:
Bank:
package com.bank;

public class BankAccount {


private int accountNo;
private String fisrtName;
private String lastName;
private double balance;
private String accType;
static int count=100;
public BankAccount(String fisrtName, String lastName, double balance, String
accType) {
super();
count++;

this.accountNo = count;
this.fisrtName = fisrtName;
this.lastName = lastName;
this.balance = balance;
this.accType = accType;
}
@Override
public String toString() {
return "BankAccount [accountNo=" + accountNo + ", fisrtName=" +
fisrtName + ", lastName=" + lastName
+ ", balance=" + balance + ", accType=" + accType + "]";
}
public void setBalance(double balance) {
this.balance=this.balance+balance;
}

public int getAccount() {


return accountNo;
}
}

Services :
package com.bank.service;

import com.bank.BankAccount;

public interface BankOperation {


public String addAccount (String fisrtName, String lastName, double balance, String
accType);
public void diplayAcc();
public String depositFund(int acNo,double balance);
}

Implementation :
package com.bank.service;

import com.bank.BankAccount;

public class BankOperationImpl implements BankOperation {


private BankAccount accounts[];
private int index;

public BankOperationImpl(int size) {


accounts=new BankAccount[size];
}

@Override
public String addAccount(String fisrtName, String lastName, double balance, String
accType) {
if(index<accounts.length) {
accounts[index]=new BankAccount(fisrtName, lastName, balance, accType);
return "account is created !!!!";
}
return "Bank have not space";
}

@Override
public void diplayAcc() {
for(BankAccount b:accounts) {
if(b!=null) {
System.out.println(b);
}
}

@Override
public String depositFund(int acNo,double balance) {
for(BankAccount b:accounts) {
if(b!=null) {
if(b.getAccount()==acNo) {
b.setBalance(balance);
return "Operation Succesful!!!!!!";
}
}
}
return "Something Wrong";
}

Handling:
package custom_handling;

public class BalanceValidationException extends Exception {


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

}
Validations:
package util;

import custom_handling.BalanceValidationException;

public class Accountsvalidation {


public static void BalanceValidation(double bal) throws BalanceValidationException{
if(bal<5000) {
throw new BalanceValidationException("Minimum balance required is 5000");
}

}
}

Tester :
package ui;

import java.util.Scanner;

import com.bank.service.BankOperationImpl;

import custom_handling.BalanceValidationException;
import util.Accountsvalidation;
public class MyBank {

public static void main(String[] args) {


try (Scanner sc = new Scanner(System.in)) {
System.out.println("Enter the Number of Accounts");
BankOperationImpl b1 = new BankOperationImpl(sc.nextInt());
boolean exit = false;
while (!exit) {
System.out.println("Options\n" + "1.Add account\n" + "2.display\n"
+ "3.deposite fund\n" + "0.Exit");
System.out.println("Enter your choice");
switch (sc.nextInt()) {
case 1:
System.out.println("Enter your details
firstname,lastname,balance,account type");
String fn=sc.next();
String ln=sc.next();
double bal=sc.nextDouble();
String at=sc.next();
Accountsvalidation. BalanceValidation(bal);
System.out.println(b1.addAccount(fn,ln,bal,at));
break;
case 2:
System.out.println("Accounts details !!!!!!!!!!");
b1.diplayAcc();
break;
case 3:
System.out.println("Enter your account number and deposit
fund");
System.out.println(b1.depositFund(sc.nextInt(),sc.nextDouble()));
break;
case 0:
System.out.println("Exiting............");
exit=true;
}
}

catch (BalanceValidationException e) {
System.out.println(e.getMessage());
}
}

}
Day 8
Bank class:
package com.bank;

import java.time.LocalDate;
import java.util.Objects;

public class BankAccount {


private int accountNo;

public double getBalance() {


return balance;
}

public BankAccount(int accountNo) {


super();
this.accountNo = accountNo;
}

private String firstName;


private String lastName;
private double balance;
private AccountTypes accType;
private LocalDate dob;

public BankAccount(int accno, String firstName, String lastName, double balance,


AccountTypes accType,
LocalDate dob) {
super();
this.dob = dob;
this.accountNo = accno;
this.firstName = firstName;
this.lastName = lastName;
this.balance = balance;
this.accType = accType;
}

@Override
public String toString() {
return "BankAccount [accountNo=" + accountNo + ", fisrtName=" + firstName + ",
lastName=" + lastName
+ ", balance=" + balance + ", accType=" + accType + ", DOB=" +
dob + "]";
}
public void setBalance(double balance) {
this.balance = balance;
}

public int getAccount() {


return accountNo;

@Override
public boolean equals(Object obj) {
if (obj instanceof BankAccount)
return this.accountNo == ((BankAccount) obj).accountNo;
return false;
}

Account type:
package com.bank;

public enum AccountTypes {


SAVING(10000), CURRENT(3000), DEMAT(5000), FD(25000), RD(30000),
NRI(100000);

private double minimumbal;

private AccountTypes(double bal) {


// TODO Auto-generated constructor stub
this.minimumbal=bal;

public double getMinimumbal() {


return minimumbal;
}

package com.bank.service;

import com.bank.BankAccount;
import custom_handling.BankException;

public interface BankOperation {


String addAccount(int accNo, String firstName, String lastName, double balance, String
accType, String dob)
throws BankException;

void displayAcc();

String depositFund(int acNo, double balance)throws BankException;

String withdrowMoney(int acNo, double balance) throws BankException;

void displaySummary(int accNo)throws BankException;

String fundTransfer(int srcAccNo, int destAccNo, double fund)throws BankException;


String closeAccount(int accNo);
}

package com.bank.service;

import java.time.LocalDate;

import com.bank.AccountTypes;
import com.bank.BankAccount;

import custom_handling.BankException;
import util.Accountsvalidation;

public class BankOperationImpl implements BankOperation {


private BankAccount accounts[];
private int index;

public BankOperationImpl(int size) {


accounts = new BankAccount[size];
}

public boolean check() {


if (index < accounts.length)
return true;
return false;
}
@Override
public String addAccount(int accNo, String firstName, String lastName, double balance,
String accType, String dob)
throws BankException {
AccountTypes type = Accountsvalidation.AccountTypeValidation(accType);
double bal = Accountsvalidation.BalanceValidation(type,balance);
LocalDate d = Accountsvalidation.parseDate(dob);
Accountsvalidation.AgeValidation(dob, d);

for (BankAccount b : accounts) {


if (b != null) {
int objaccNo = b.getAccount();
accNo = Accountsvalidation.AccountValidation(objaccNo, accNo);
}
}
accounts[index++] = new BankAccount(accNo, firstName, lastName, bal, type,
d);
return "account is created !!!!";

@Override
public void displayAcc() {
for (BankAccount b : accounts) {
if (b != null) {
System.out.println(b);
}
}

@Override
public void displaySummary(int accNo) throws BankException {
for (BankAccount b : accounts) {
if (b != null) {
if (b.getAccount() == accNo) {
System.out.println(b);
}
}
}
throw new BankException("Account not found!!!!");

}
@Override
public String depositFund(int acNo, double balance) {
for (BankAccount b : accounts) {
if (b != null) {
if (b.getAccount() == acNo) {
b.setBalance(b.getBalance() + balance);
return "Operation Succesful!!!!!!";
}
}
}
return "Something Wrong";
}

@Override
public String withdrowMoney(int acNo, double balance) throws BankException {
for (BankAccount b : accounts) {
if (b != null) {
if (b.getAccount() == acNo) {
if (b.getBalance() < balance)
throw new BankException("Insufficient
balance!!!!!");
else if (b.getBalance() - balance < 5000)
throw new BankException(
"You have to maintain minumum
balance your balance is : " + b.getBalance());
else {
b.setBalance(b.getBalance() - balance);
return "Operation Succesful!!!!!!";
}
}
}
}
return "Something Wrong";
}

@Override
public String fundTransfer(int srcAccNo, int destAccNo, double fund) throws
BankException {
for (BankAccount b : accounts) {
if (b != null) {
if (b.getAccount() == srcAccNo) {
if (b.getBalance() < fund)
throw new BankException("Insufficient
balance!!!!!");
else if (b.getBalance() - fund < 5000)
throw new BankException(
"You have to maintain minumum
balance your balance is : " + b.getBalance());
else {
double bal = b.getBalance() - fund;
b.setBalance(bal);
}

}
}
}
for (BankAccount b : accounts) {
if (b != null) {
if (b.getAccount() == destAccNo) {
double bal = b.getBalance() + fund;
b.setBalance(bal);
}
}
}
return "Operation Succesful!!!!!!";
}

public String closeAccount(int accNo) {


for (int i=0;i<accounts.length;i++) {
if (accounts[i] != null) {
if (accounts[i].getAccount() == accNo) {
accounts[i]=null;
return "Account is closed!!!!";
}
}
}
return "Something is wrong";
}

package com.bank.service;

import java.time.LocalDate;
import java.util.ArrayList;

import com.bank.AccountTypes;
import com.bank.BankAccount;
import custom_handling.BankException;
import util.Accountsvalidation;

public class BankOperationImplArrayList implements BankOperation {


private ArrayList<BankAccount> accounts;

public BankOperationImplArrayList() {

accounts = new ArrayList<>();


}

@Override
public String addAccount(int accNo, String firstName, String lastName, double balance,
String accType, String dob)
throws BankException {
AccountTypes type = Accountsvalidation.AccountTypeValidation(accType);

double bal = Accountsvalidation.BalanceValidation(type, balance);


LocalDate d = Accountsvalidation.parseDate(dob);
Accountsvalidation.AgeValidation(dob, d);
BankAccount acc = new BankAccount(accNo);

if (accounts.contains(acc)) {
throw new BankException("Account number already exist!!!!");
}

BankAccount b = new BankAccount(accNo, firstName, lastName, bal, type, d);


accounts.add(b);
return "account is created !!!!";

@Override
public void displayAcc() {
for (BankAccount b : accounts) {
System.out.println(b);
}

@Override
public String depositFund(int acNo, double balance) throws BankException {
int index = getIndex(acNo);
if (index != -1) {
BankAccount b = accounts.get(index);
b.setBalance(b.getBalance() + balance);
return "Operation Succesful!!!!!!";

}
throw new BankException("Account not found");

@Override
public String withdrowMoney(int acNo, double balance) throws BankException {
int index = getIndex(acNo);
balanceCheck(acNo,balance);
return "Operation Successfull!!!!";
}

@Override
public void displaySummary(int accNo) throws BankException {
int index = getIndex(accNo);
if (index == -1) {
throw new BankException("Account not found!!!!");
}
System.out.println(accounts.get(index));

@Override
public String fundTransfer(int srcAccNo, int destAccNo, double fund) throws
BankException {
balanceCheck(srcAccNo, fund);
int index =getIndex(destAccNo);
if (index != -1) {
BankAccount b = accounts.get(index);
double bal = b.getBalance() + fund;
b.setBalance(bal);
return "Operation Succesful!!!!!!";
}

throw new BankException("Account not found");


}

public String closeAccount(int accNo) {


int index = getIndex(accNo);
if (index != -1) {
accounts.remove(index);
return "Account closed!!!!";
}
return "Something is wrong";
}
private int getIndex(int accNo) {
BankAccount acc = new BankAccount(accNo);
int index = accounts.indexOf(acc);
return index;
}
private void balanceCheck(int accNo,double fund) throws BankException{
int index = getIndex(accNo);
if (index != -1) {
BankAccount b = accounts.get(index);
if (b.getBalance() < fund)
throw new BankException("Insufficient balance!!!!!");
else if (b.getBalance() - fund < 5000)
throw new BankException("You have to maintain minumum
balance your balance is : " + b.getBalance());
else {
double bal = b.getBalance() - fund;
b.setBalance(bal);
}
}
}

Handling:
package custom_handling;

@SuppressWarnings("serial")
public class BankException extends Exception {
public BankException(String msg) {
super(msg);
}

Validations :
package util;
import java.time.LocalDate;
import java.time.Period;

import com.bank.AccountTypes;

import custom_handling.BankException;

public class Accountsvalidation {

public static double BalanceValidation(AccountTypes type,double bal) throws BankException{


if(bal<type.getMinimumbal()) {
throw new BankException("Minimum balance required!!!");
}
return bal;

}
public static AccountTypes AccountTypeValidation(String actype) throws
IllegalArgumentException {
AccountTypes type=AccountTypes.valueOf(actype.toUpperCase());
return type;
}
public static void AgeValidation(String dob,LocalDate date) throws BankException{

int age=Period.between(date,LocalDate.now()).getYears();
if(age<18)
throw new BankException("you are below 18");

public static int AccountValidation(int objaccNo,int accNo) throws BankException{


if(objaccNo==accNo)
throw new BankException("Account number already exist!!!!");
return accNo;
}
public static LocalDate parseDate(String dob) {
return LocalDate.parse(dob);
}
}

Tester :
package ui;

import java.util.Scanner;
import com.bank.service.BankOperationImpl;
import com.bank.service.BankOperationImplArrayList;

import custom_handling.BankException;
import util.Accountsvalidation;

public class MyBank {

public static void main(String[] args) {


try (Scanner sc = new Scanner(System.in)) {
System.out.println("Welcome to Bank Management System�嬉沽嬉
沽� ");
// System.out.println("Enter the Number of Accounts");
// BankOperationImpl b1 = new BankOperationImpl(sc.nextInt());
BankOperationImplArrayList b1 = new BankOperationImplArrayList();
boolean exit = false;
while (!exit) {
try {
System.out.println("Options\n" + "1.Add Account\n" +
"2.Deposite fund\n" + "3.Withdraw Money \n"
+ "4.Display All Accounts Details\n" +
"5.Display Account Summary\n" + "6.Transfer Money\n"
+ "7.Close Account\n" + "0.Exit");
System.out.println("Enter your choice");
switch (sc.nextInt()) {
case 1:
// if(b1.check()) {
System.out.println(
"Enter account details : account
number ,firstname,lastname,balance,account type,date of birth");
System.out.println(b1.addAccount(sc.nextInt(),
sc.next(), sc.next(), sc.nextDouble(), sc.next(),
sc.next()));

// else System.out.println("No space available for new


accounts");
break;

case 2:
System.out.println("Enter your account number and
deposit fund");
System.out.println(b1.depositFund(sc.nextInt(),
sc.nextDouble()));
break;
case 3:
System.out.println("Enter the account number and
ammount");
System.out.println(b1.withdrowMoney(sc.nextInt(),
sc.nextDouble()));
break;
case 4:
System.out.println("Accounts details !!!!!!!!!!");
b1.displayAcc();
break;
case 5:
System.out.println("Enter your Account number");
b1.displaySummary(sc.nextInt());
break;
case 6:

System.out.println("Enter your account number and


your friend account number and fund");
System.out.println(b1.fundTransfer(sc.nextInt(),
sc.nextInt(), sc.nextDouble()));
break;
case 7:
System.out.println("Enter your Account Number");
System.out.println(b1.closeAccount(sc.nextInt()));
break;
case 0:
System.out.println("Exiting............");
exit = true;
}
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println("Pls Try again!!!!");
sc.nextLine();
}
}
}

// catch (BalanceValidationException e) {
// System.out.println(e.getMessage());
// }
}

}
Day 9 and 10:
package core.customer;

import java.time.LocalDate;

public class Customer {


private int customerId;
private String firstname;
private String lasttname;
private String email;
private String password;

public String getFirstname() {


return firstname;
}

public Customer(String email) {


super();
this.email = email;
}

public String getLasttname() {


return lasttname;
}

private double resAmmount;


private LocalDate dob;
private ServicePlan plan;
public static int count = 100;

public Customer(String firstname, String lasttname, String email, String password,


double resAmmount, LocalDate dob, ServicePlan plan) {

this.customerId = count++;
this.firstname = firstname;
this.lasttname = lasttname;
this.email = email;
this.password = password;
this.resAmmount = resAmmount;
this.dob = dob;
this.plan = plan;
}

public void setPassword(String password) {


this.password = password;
}

public String getEmail() {


return email;
}

public String getPassword() {


return password;
}

public int getCustomerId() {


return customerId;
}

@Override
public String toString() {
return "Customer [customerId=" + customerId + ", firstname=" + firstname + ",
lasttname=" + lasttname
+ ", email=" + email + ", password=********" + ", resAmmount=" +
resAmmount + ", dob=" + dob
+ ", plan=" + plan + "]";
}

@Override
public boolean equals(Object obj) {
if (obj instanceof Customer) {
Customer other = (Customer) obj;
return this.email.equals(other.email);
}
return false;
}
}

—----------------------------------------------------------------------------------------------------------------------------
package core.customer;

public enum ServicePlan {


SILVER(1000), GOLD(2000), DIAMOND(5000), PLATINUM(10000);

/// add a field


private double planCost;

private ServicePlan(double planCost) {


this.planCost = planCost;
}
public double getPlanCost() {
return planCost;
}
}

—----------------------------------------------------------------------------------------------------------------------------
package core.customer.custom_exception;

@SuppressWarnings("serial")
public class CustomerException extends Exception {

public CustomerException(String msg) {


super(msg);
}

}
—----------------------------------------------------------------------------------------------------------------------------
package core.customer.services;

import core.customer.custom_exception.CustomerException;

public interface CustomerOperations {


String signUp(String firstname, String lasttname, String email, String password, double
resAmmount, String dob,
String plan) throws IllegalArgumentException, CustomerException;

void display();

String signIn(String email, String password) throws CustomerException;

String changePassword(String email, String oldpass, String newpass) throws


CustomerException;

String unsuscribeCustomer(String email) throws CustomerException;

}
—----------------------------------------------------------------------------------------------------------------------------
package core.customer.services;

import java.time.LocalDate;

import core.customer.Customer;
import core.customer.ServicePlan;
import core.customer.custom_exception.CustomerException;
import core.customer.validation.CustomerValidation;

public class CustomerOperationsImpl implements CustomerOperations {

private Customer[] customers;


private int index = 0;

public CustomerOperationsImpl(int size) {


customers = new Customer[size];
}

public boolean check() {


if (index < customers.length)
return true;
return false;
}

public Customer emailFind(String email) throws CustomerException {


for (Customer c : customers) {
if (c != null) {
if (c.getEmail().equals(email))
return c;
}
}

throw new CustomerException("Invalid Email!!!!");


}

@Override
public String signUp(String firstname, String lasttname, String email, String password,
double resAmmount,
String dob, String plan) throws IllegalArgumentException,
CustomerException {
LocalDate d = CustomerValidation.parseDate(dob);
ServicePlan p = CustomerValidation.validatePlanAndRegAmount(plan,
resAmmount);
CustomerValidation.emailValidation(email);
CustomerValidation.passwordValidation(password);
Customer c = new Customer(firstname, lasttname, email, password,
resAmmount, d, p);
customers[index++] = c;
return "registration successfull!!!! with id :" + c.getCustomerId();
}

@Override
public void display() {
System.out.println("All customer details !!!!!");
for (Customer c : customers) {
if (c != null)
System.out.println(c);
}
}

@Override
public String signIn(String email, String password) throws CustomerException {
Customer c = emailFind(email);
if (c.getPassword().equals(password))
return "Sign In Successfully ! Hello " + c.getFirstname() + " " +
c.getLasttname();
throw new CustomerException("Invalid password!!!!!!!!!");
}

@Override
public String changePassword(String email, String oldpass, String newpass) throws
CustomerException {
Customer c = emailFind(email);
if (c.getPassword().equals(oldpass)) {
c.setPassword(newpass);
return "Successful password updation on cutomer id : " +
c.getCustomerId();
}
throw new CustomerException("Invalid password!!!!!!!!!");
}

@Override
public String unsuscribeCustomer(String email) throws CustomerException {
for (int i = 0; i < customers.length; i++) {
Customer c = customers[i];
if (c != null) {
if (c.getEmail().equals(email)) {
customers[i] = null;
return "Your are Unsuscribed!!!!!";
}
}
}
throw new CustomerException("Invalid email !!!!!!!");
}

—----------------------------------------------------------------------------------------------------------------------------
package core.customer.services;

import java.time.LocalDate;
import java.util.ArrayList;

import core.customer.Customer;
import core.customer.ServicePlan;
import core.customer.custom_exception.CustomerException;
import core.customer.validation.CustomerValidation;

public class CustomerOperationImplArrayList implements CustomerOperations {


private ArrayList<Customer> customers;

public CustomerOperationImplArrayList() {
customers = new ArrayList<>();
}

public Customer emailFind(String email) throws CustomerException {


Customer c = new Customer(email);
int index = customers.indexOf(c);
if (index == -1)
throw new CustomerException("Invalid Email!!!!");
return customers.get(index);
}

@Override
public String signUp(String firstname, String lasttname, String email, String password,
double resAmmount,
String dob, String plan) throws IllegalArgumentException,
CustomerException {
LocalDate d = CustomerValidation.parseDate(dob);
ServicePlan p = CustomerValidation.validatePlanAndRegAmount(plan,
resAmmount);
CustomerValidation.emailValidation(email);
CustomerValidation.passwordValidation(password);
Customer c = new Customer(firstname, lasttname, email, password,
resAmmount, d, p);
customers.add(c);
return "registration successfull!!!! with id :" + c.getCustomerId();

@Override
public void display() {
System.out.println("All customer details !!!!!");
for (Customer c : customers) {
System.out.println(c);
}

@Override
public String signIn(String email, String password) throws CustomerException {
Customer c = emailFind(email);
if (c.getPassword().equals(password))
return "Sign In Successfully ! Hello " + c.getFirstname() + " " +
c.getLasttname();
throw new CustomerException("Invalid password!!!!!!!!!");
}

@Override
public String changePassword(String email, String oldpass, String newpass) throws
CustomerException {
Customer c = emailFind(email);
if (c.getPassword().equals(oldpass)) {
c.setPassword(newpass);
return "Successful password updation on cutomer id : " +
c.getCustomerId();
}
throw new CustomerException("Invalid password!!!!!!!!!");
}

@Override
public String unsuscribeCustomer(String email) throws CustomerException {
for (int i = 0; i < customers.size(); i++) {
Customer c =customers.get(i);

if (c.getEmail().equals(email)) {
customers.remove(i);
return "Your are Unsuscribed!!!!!";
}
}
throw new CustomerException("Invalid email !!!!!!!");
}

}
—----------------------------------------------------------------------------------------------------------------------------
package core.customer.services;

import java.time.LocalDate;

import core.customer.Customer;
import core.customer.ServicePlan;
import core.customer.custom_exception.CustomerException;
import core.customer.validation.CustomerValidation;

public class CustomerOperationsImpl implements CustomerOperations {

private Customer[] customers;


private int index = 0;

public CustomerOperationsImpl(int size) {


customers = new Customer[size];
}

public boolean check() {


if (index < customers.length)
return true;
return false;
}

public Customer emailFind(String email) throws CustomerException {


for (Customer c : customers) {
if (c != null) {
if (c.getEmail().equals(email))
return c;
}
}

throw new CustomerException("Invalid Email!!!!");


}

@Override
public String signUp(String firstname, String lasttname, String email, String password,
double resAmmount,
String dob, String plan) throws IllegalArgumentException,
CustomerException {
LocalDate d = CustomerValidation.parseDate(dob);
ServicePlan p = CustomerValidation.validatePlanAndRegAmount(plan,
resAmmount);
CustomerValidation.emailValidation(email);
CustomerValidation.passwordValidation(password);
Customer c = new Customer(firstname, lasttname, email, password,
resAmmount, d, p);
customers[index++] = c;
return "registration successfull!!!! with id :" + c.getCustomerId();

@Override
public void display() {
System.out.println("All customer details !!!!!");
for (Customer c : customers) {
if (c != null)
System.out.println(c);
}
}

@Override
public String signIn(String email, String password) throws CustomerException {
Customer c = emailFind(email);
if (c.getPassword().equals(password))
return "Sign In Successfully ! Hello " + c.getFirstname() + " " +
c.getLasttname();
throw new CustomerException("Invalid password!!!!!!!!!");
}

@Override
public String changePassword(String email, String oldpass, String newpass) throws
CustomerException {
Customer c = emailFind(email);
if (c.getPassword().equals(oldpass)) {
c.setPassword(newpass);
return "Successful password updation on cutomer id : " +
c.getCustomerId();
}
throw new CustomerException("Invalid password!!!!!!!!!");
}
@Override
public String unsuscribeCustomer(String email) throws CustomerException {
for (int i = 0; i < customers.length; i++) {
Customer c = customers[i];
if (c != null) {
if (c.getEmail().equals(email)) {
customers[i] = null;
return "Your are Unsuscribed!!!!!";
}
}
}
throw new CustomerException("Invalid email !!!!!!!");
}

—----------------------------------------------------------------------------------------------------------------------------
package core.customer.validation;

import java.time.LocalDate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import core.customer.ServicePlan;
import core.customer.custom_exception.CustomerException;

public class CustomerValidation {


public static ServicePlan validatePlanAndRegAmount(String plan,double regAmount)
throws IllegalArgumentException,CustomerException{
ServicePlan p=ServicePlan.valueOf(plan.toUpperCase());
if(p.getPlanCost()!= regAmount) {
throw new CustomerException("plan not exist with registration ammount");
}
return p;
}
public static void emailValidation(String email) throws CustomerException {
String e= "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}$";
Pattern p = Pattern.compile(e);
Matcher m = p.matcher(email);
if(!m.matches()) throw new CustomerException("Email is incorrect should be like
[email protected]!!!!!!");

}
public static void passwordValidation(String password) throws CustomerException {
String pass="^\\d{8}$";
Pattern p = Pattern.compile(pass);
Matcher m = p.matcher(password);
if(!m.matches()) throw new CustomerException("Password must be exactly 8 digits
(e.g., 12345678)!!!!!!");

}
public static LocalDate parseDate(String dob)throws IllegalArgumentException{
return LocalDate.parse(dob);
}

—----------------------------------------------------------------------------------------------------------------------------
package core.customer.tester;

import java.util.Scanner;

import core.customer.services.CustomerOperationImplArrayList;
import core.customer.services.CustomerOperationsImpl;

public class CustomerManagementSystem {

public static void main(String[] args) {


try (Scanner sc = new Scanner(System.in)) {
System.out.println("Welcome to Customer Management System
�嬉沽嬉沽嬉沽�");
// System.out.println("Enter the capacity of customers");
// CustomerOperationsImpl op = new
CustomerOperationsImpl(sc.nextInt());
CustomerOperationImplArrayList op = new
CustomerOperationImplArrayList();
boolean exit = false;
while (!exit) {
System.out.println("Options--------------------\n" + "1.Registration \n"
+ "2.Sign In\n"
+ "3.Change Password\n" + "4.Unsuscribe\n" +
"5.Display All Accounts\n" + "0.exit");
System.out.println("Enter your choice");
try {
switch (sc.nextInt()) {
case 1:
System.out.println("Enter your details -
FirstName,Lastname,Email,pass,regAmount,dob,plan");
System.out.println(op.signUp(sc.next(), sc.next(),
sc.next(), sc.next(), sc.nextDouble(),
sc.next(), sc.next()));

break;
case 2:
System.out.println("Enter your email and
password");
System.out.println(op.signIn(sc.next(), sc.next()));
break;
case 3:
System.out.println("Enter your email, old
password,new password");
System.out.println(op.changePassword(sc.next(),
sc.next(), sc.next()));
break;
case 4:
System.out.println("Enter your email");

System.out.println(op.unsuscribeCustomer(sc.next()));
break;
case 5:
op.display();
break;
case 0:
System.out.println("Exiting...........");
exit = true;
break;

}
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println("Pls retry ...");
sc.nextLine();
}
}
}

}
Day 11 - 12
package com.bank;

import java.time.LocalDate;
import java.util.Objects;

public class BankAccount implements Comparable<BankAccount> {


private int accountNo;

public double getBalance() {


return balance;
}

public BankAccount(int accountNo) {


super();
this.accountNo = accountNo;
}

private String firstName;


private String lastName;
private double balance;
private AccountTypes accType;
private LocalDate dob;

public BankAccount(int accno, String firstName, String lastName, double balance,


AccountTypes accType,
LocalDate dob) {
super();
this.dob = dob;
this.accountNo = accno;
this.firstName = firstName;
this.lastName = lastName;
this.balance = balance;
this.accType = accType;
}

@Override
public String toString() {
return "BankAccount [accountNo=" + accountNo + ", fisrtName=" + firstName + ",
lastName=" + lastName
+ ", balance=" + balance + ", accType=" + accType + ", DOB=" +
dob + "]";
}
public void setBalance(double balance) {
this.balance = balance;
}

public AccountTypes getAccType() {


return accType;
}

public int getAccount() {


return accountNo;

public LocalDate getDob() {


return dob;
}

@Override
public boolean equals(Object obj) {
if (obj instanceof BankAccount)
return this.accountNo == ((BankAccount) obj).accountNo;
return false;
}

@Override
public int compareTo(BankAccount o) {
if(this.accountNo<o.accountNo)return -1;
else if(this.accountNo==o.accountNo) return 0;
else return 1;
}

package com.bank;

public enum AccountTypes {


SAVING(10000), CURRENT(3000), DEMAT(5000), FD(25000), RD(30000),
NRI(100000);

private double minimumbal;

private AccountTypes(double bal) {


// TODO Auto-generated constructor stub
this.minimumbal=bal;
}

public double getMinimumbal() {


return minimumbal;
}

package com.bank.service;

import com.bank.BankAccount;

import custom_handling.BankException;

public interface BankOperation {


String addAccount(int accNo, String firstName, String lastName, double balance, String
accType, String dob)
throws BankException;

void displayAcc();

String depositFund(int acNo, double balance)throws BankException;

String withdrowMoney(int acNo, double balance) throws BankException;

void displaySummary(int accNo)throws BankException;

String fundTransfer(int srcAccNo, int destAccNo, double fund)throws BankException;


String closeAccount(int accNo);
void sortByAccountNo();
void sortByAccounttype();
void sortByDOBandBalance();
}

package com.bank.service;

import java.time.LocalDate;

import com.bank.AccountTypes;
import com.bank.BankAccount;

import custom_handling.BankException;
import static util.Accountsvalidation.*;

public class BankOperationImpl implements BankOperation {


private BankAccount accounts[];
private int index;

public BankOperationImpl(int size) {


accounts = new BankAccount[size];
}

public boolean check() {


if (index < accounts.length)
return true;
return false;
}

@Override
public String addAccount(int accNo, String firstName, String lastName, double balance,
String accType, String dob)
throws BankException {
AccountTypes type = AccountTypeValidation(accType);
double bal = BalanceValidation(type,balance);
LocalDate d = parseDate(dob);
AgeValidation(dob, d);
for (BankAccount b : accounts) {
if (b != null) {
int objaccNo = b.getAccount();
accNo = AccountValidation(objaccNo, accNo);
}
}
accounts[index++] = new BankAccount(accNo, firstName, lastName, bal, type,
d);
return "account is created !!!!";

@Override
public void displayAcc() {
for (BankAccount b : accounts) {
if (b != null) {
System.out.println(b);
}
}
}

@Override
public void displaySummary(int accNo) throws BankException {
for (BankAccount b : accounts) {
if (b != null) {
if (b.getAccount() == accNo) {
System.out.println(b);
}
}
}
throw new BankException("Account not found!!!!");

@Override
public String depositFund(int acNo, double balance) {
for (BankAccount b : accounts) {
if (b != null) {
if (b.getAccount() == acNo) {
b.setBalance(b.getBalance() + balance);
return "Operation Succesful!!!!!!";
}
}
}
return "Something Wrong";
}

@Override
public String withdrowMoney(int acNo, double balance) throws BankException {
for (BankAccount b : accounts) {
if (b != null) {
if (b.getAccount() == acNo) {
if (b.getBalance() < balance)
throw new BankException("Insufficient
balance!!!!!");
else if (b.getBalance() - balance < 5000)
throw new BankException(
"You have to maintain minumum
balance your balance is : " + b.getBalance());
else {
b.setBalance(b.getBalance() - balance);
return "Operation Succesful!!!!!!";
}
}
}
}
return "Something Wrong";
}

@Override
public String fundTransfer(int srcAccNo, int destAccNo, double fund) throws
BankException {
for (BankAccount b : accounts) {
if (b != null) {
if (b.getAccount() == srcAccNo) {
if (b.getBalance() < fund)
throw new BankException("Insufficient
balance!!!!!");
else if (b.getBalance() - fund < 5000)
throw new BankException(
"You have to maintain minumum
balance your balance is : " + b.getBalance());
else {
double bal = b.getBalance() - fund;
b.setBalance(bal);
}

}
}
}
for (BankAccount b : accounts) {
if (b != null) {
if (b.getAccount() == destAccNo) {
double bal = b.getBalance() + fund;
b.setBalance(bal);
}
}
}
return "Operation Succesful!!!!!!";
}

public String closeAccount(int accNo) {


for (int i=0;i<accounts.length;i++) {
if (accounts[i] != null) {
if (accounts[i].getAccount() == accNo) {
accounts[i]=null;
return "Account is closed!!!!";
}
}
}
return "Something is wrong";
}

@Override
public void sortByAccountNo() {
// TODO Auto-generated method stub

@Override
public void sortByAccounttype() {
// TODO Auto-generated method stub

@Override
public void sortByDOBandBalance() {
// TODO Auto-generated method stub

package com.bank.service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;

import com.bank.AccountTypes;
import com.bank.BankAccount;

import custom_handling.BankException;
import static util.Accountsvalidation.*;

public class BankOperationImplArrayList implements BankOperation {


private ArrayList<BankAccount> accounts;

public BankOperationImplArrayList() {
accounts = new ArrayList<>();

@Override
public String addAccount(int accNo, String firstName, String lastName, double balance,
String accType, String dob)
throws BankException {
AccountTypes type = AccountTypeValidation(accType);

double bal = BalanceValidation(type, balance);


LocalDate d = parseDate(dob);
AgeValidation(dob, d);
BankAccount acc = new BankAccount(accNo);

if (accounts.contains(acc)) {
throw new BankException("Account number already exist!!!!");
}

BankAccount b = new BankAccount(accNo, firstName, lastName, bal, type, d);


accounts.add(b);
return "account is created !!!!";

@Override
public void displayAcc() {
for (BankAccount b : accounts) {
System.out.println(b);
}

@Override
public String depositFund(int acNo, double balance) throws BankException {
int index = getIndex(acNo);
if (index != -1) {
BankAccount b = accounts.get(index);
b.setBalance(b.getBalance() + balance);
return "Operation Succesful!!!!!!";

}
throw new BankException("Account not found");
}

@Override
public String withdrowMoney(int acNo, double balance) throws BankException {
balanceCheck(acNo,balance);
return "Operation Successfull!!!!";
}

@Override
public void displaySummary(int accNo) throws BankException {
int index = getIndex(accNo);
if (index == -1) {
throw new BankException("Account not found!!!!");
}
System.out.println(accounts.get(index));

@Override
public String fundTransfer(int srcAccNo, int destAccNo, double fund) throws
BankException {
balanceCheck(srcAccNo, fund);
int index =getIndex(destAccNo);
if (index != -1) {
BankAccount b = accounts.get(index);
double bal = b.getBalance() + fund;
b.setBalance(bal);
return "Operation Succesful!!!!!!";
}

throw new BankException("Account not found");


}
@Override
public String closeAccount(int accNo) {

int index = getIndex(accNo);


if (index != -1) {
accounts.remove(index);
return "Account closed!!!!";
}
return "Something is wrong";
}
private int getIndex(int accNo) {
BankAccount acc = new BankAccount(accNo);
int index = accounts.indexOf(acc);
return index;
}
private void balanceCheck(int accNo,double fund) throws BankException{
int index = getIndex(accNo);
if (index != -1) {
BankAccount b = accounts.get(index);
if (b.getBalance() < fund)
throw new BankException("Insufficient balance!!!!!");
else if (b.getBalance() - fund < 5000)
throw new BankException("You have to maintain minumum
balance your balance is : " + b.getBalance());
else {
double bal = b.getBalance() - fund;
b.setBalance(bal);
}
}
}
@Override
public void sortByAccountNo() {

Collections.sort(accounts);
System.out.println("Operation done!!!!");
}
@Override
public void sortByAccounttype() {
Collections.sort(accounts,new Comparator<BankAccount>() {

@Override
public int compare(BankAccount o1, BankAccount o2) {
return o1.getAccType().compareTo(o2.getAccType());

});
System.out.println("Operation done!!!!");
}
@Override
public void sortByDOBandBalance() {
Collections.sort(accounts,new Comparator<BankAccount>() {

@Override
public int compare(BankAccount o1, BankAccount o2) {
int typeval=o1.getDob().compareTo(o2.getDob());
if(typeval==0){
// if(o1.getBalance()<o2.getBalance())return -1;
// else if(o1.getBalance()==o2.getBalance())return 0;
// return 1;
return ((Double)o1.getBalance()).compareTo(o2.getBalance());//it is
compreTo method of Double so in o2 its auto boxing double to Double
}

return typeval;
}

});
System.out.println("Operation done!!!!");
}

package custom_handling;

@SuppressWarnings("serial")
public class BankException extends Exception {
public BankException(String msg) {
super(msg);
}

package util;

import java.time.LocalDate;
import java.time.Period;

import com.bank.AccountTypes;

import custom_handling.BankException;

public class Accountsvalidation {

public static double BalanceValidation(AccountTypes type,double bal) throws BankException{


if(bal<type.getMinimumbal()) {
throw new BankException("Minimum balance required!!!");
}
return bal;

}
public static AccountTypes AccountTypeValidation(String actype) throws
IllegalArgumentException {
AccountTypes type=AccountTypes.valueOf(actype.toUpperCase());
return type;
}
public static void AgeValidation(String dob,LocalDate date) throws BankException{

int age=Period.between(date,LocalDate.now()).getYears();
if(age<18)
throw new BankException("you are below 18");

public static int AccountValidation(int objaccNo,int accNo) throws BankException{


if(objaccNo==accNo)
throw new BankException("Account number already exist!!!!");
return accNo;
}
public static LocalDate parseDate(String dob) {
return LocalDate.parse(dob);
}
}

package ui;

import java.util.Scanner;

import com.bank.service.BankOperationImpl;
import com.bank.service.BankOperationImplArrayList;

import custom_handling.BankException;
import util.Accountsvalidation;

public class MyBank {

public static void main(String[] args) {


try (Scanner sc = new Scanner(System.in)) {
System.out.println("Welcome to Bank Management System�嬉沽嬉
沽� ");
// System.out.println("Enter the Number of Accounts");
// BankOperationImpl b1 = new BankOperationImpl(sc.nextInt());
BankOperationImplArrayList b1 = new BankOperationImplArrayList();
boolean exit = false;
while (!exit) {
try {
System.out.println("Options\n" + "1.Add Account\n" +
"2.Deposite fund\n" + "3.Withdraw Money \n"
+ "4.Display All Accounts Details\n" +
"5.Display Account Summary\n" + "6.Transfer Money\n"
+ "7.Close Account\n"
+ "8.Sort by Acconut number\n"
+ "9.Sort bank accounts as per acct type -
custom order with ano inner class\n"
+ "10.Sort bank accounts as per customer's
dob n balance - custom order with ano inner class\n"
+ "0.Exit");
System.out.println("Enter your choice");
switch (sc.nextInt()) {
case 1:
// if(b1.check()) {
System.out.println(
"Enter account details : account
number ,firstname,lastname,balance,account type,date of birth");
System.out.println(b1.addAccount(sc.nextInt(),
sc.next(), sc.next(), sc.nextDouble(), sc.next(),
sc.next()));

// else System.out.println("No space available for new


accounts");
break;

case 2:
System.out.println("Enter your account number and
deposit fund");
System.out.println(b1.depositFund(sc.nextInt(),
sc.nextDouble()));
break;
case 3:
System.out.println("Enter the account number and
ammount");
System.out.println(b1.withdrowMoney(sc.nextInt(),
sc.nextDouble()));
break;
case 4:
System.out.println("Accounts details !!!!!!!!!!");
b1.displayAcc();
break;
case 5:
System.out.println("Enter your Account number");
b1.displaySummary(sc.nextInt());
break;
case 6:

System.out.println("Enter your account number and


your friend account number and fund");
System.out.println(b1.fundTransfer(sc.nextInt(),
sc.nextInt(), sc.nextDouble()));
break;
case 7:
System.out.println("Enter your Account Number");
System.out.println(b1.closeAccount(sc.nextInt()));
break;
case 8:
b1.sortByAccountNo();
break;
case 9:
b1.sortByAccounttype();
break;
case 10:
b1.sortByDOBandBalance();
break;
case 0:
System.out.println("Exiting............");
exit = true;
}
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println("Pls Try again!!!!");
sc.nextLine();
}
}

// catch (BalanceValidationException e) {
// System.out.println(e.getMessage());
// }
}

Day 13
package com.app.core;

public class Student {


public void setMarks(int marks) {
this.marks = marks;
}

private String rollNo;


private String name;
private int marks;

public int getMarks() {


return marks;
}

public Student(String rollNo, String name, int marks) {


super();
this.rollNo = rollNo;
this.name = name;
this.marks = marks;
}

@Override
public String toString() {
return "Student [rollNo=" + rollNo + ", name=" + name + ", marks=" + marks + "]";
}
//override equals to replace ref equality by content eq - PK (UID) - identitty
// @Override
// public boolean equals(Object o)
// {
// System.out.println("in student eq");
// if(o instanceof Student)
// {
// Student s=(Student)o;
// return this.rollNo.equals(s.rollNo);
// }
// return false;
// }
//override hashCode to satisfy the contract between equals n hashCode
// @Override
// public int hashCode() {
// System.out.println("in student hashCode");
//// return 100;
// return this.rollNo.hashCode();
// }

public String getRollNo() {


return rollNo;
}

public String getName() {


return name;
}

package com.app.core;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;

public class TestStudentMap {

public static void main(String[] args) {


try (Scanner sc = new Scanner(System.in)) {
// create empty HashMap to store student details - init capa =128
HashMap<String, Student> students = new HashMap<>(128);
System.out.println(students);// {}
// populate the map
System.out.println("rets " + students.put("dac-0009", new Student("dac-
009", "Rama", 80)));
System.out.println("rets " + students.put("dac-0009", new Student("dac-
009", "Mihir", 70)));
System.out.println("rets " + students.put("dac-0031", new Student("dac-
0031", "Kiran", 85)));
System.out.println("rets " + students.put("dac-0015", new Student("dac-
0015", "Souma", 76)));
System.out.println("rets " + students.put("dac-0024", new Student("dac-
0024", "Samay", 72)));
System.out.println("rets " + students.putIfAbsent("dac-0009", new
Student("dac-009", "Riya", 71)));
// System.out.println(students);
// display student details - on separate lines
System.out.println("All students - ");
for (Student s : students.values())// Collection<Student>
System.out.println(s);

//// ----------------get student detail


// System.out.println("enter the roll no : ");
// String roll=sc.next();
// Student s=students.get(roll);
// if(s!=null) {
// System.out.println(s);
// }
// else System.out.println("invalid roll number!!!");

//// ---------------- cancle admission


// System.out.println("enter the roll no : ");
// String roll = sc.next();
// Student s = students.remove(roll);
// if (s != null) {
// System.out.println("removed : "+s);
// } else
// System.out.println("invalid roll number!!!");
// System.out.println("-----------------");
// for (Student f : students.values())// Collection<Student>
// System.out.println(f);

//// ---------------- update marks


// System.out.println("enter the roll no and new marks ");
// String roll = sc.next();
// int marks = sc.nextInt();
//
// Student s = students.get(roll);
// if (s != null) {
// s.setMarks(marks);
// System.out.println("updated : "+s);
// }
// else {
// System.out.println("invalid roll number!!!");
// }
// for (Student f : students.values())// Collection<Student>
// System.out.println(f);

//// ---------------- display who has marks>given marks


//// System.out.println("enter the marks");
//// int marks = sc.nextInt();
//// for (Student s : students.values()) {// Collection<Student>
//// if (s.getMarks() > marks) {
//// System.out.println(s.getName());
//// }
// }

// //// ---------------- sort by roll no asc


// System.out.println("-----------------");
// TreeMap<String, Student> tree=new TreeMap<>(students);
// for(Student s:tree.values()) {
// System.out.println(s);
// }

//// ---------------- sort by roll no desc


// System.out.println("-----------------");
// TreeMap<String, Student> tree= new TreeMap<String, Student>(new
Comparator<String>() {
//
// @Override
// public int compare(String o1, String o2) {
// return o2.compareTo(o1);
// }
//
// });
// tree.putAll(students);
// for(Student s:tree.values()) {
// System.out.println(s);
// }
//

// //// ---------------- sort by name no asc


// System.out.println("-----------------");
// ArrayList<Student> arr = new ArrayList<Student>(students.values());
// Collections.sort(arr, new Comparator<Student>() {
//
// @Override
// public int compare(Student o1, Student o2) {
//
// return o1.getName().compareTo(o2.getName());
// }
//
// });
// for(Student s:arr) {
// System.out.println(s.getName());
//
// }

//// ---------------- Delete student details having marks < specified marks
System.out.println("-----------------");
System.out.println("enter the marks");
int marks = sc.nextInt();

Iterator<Map.Entry<String, Student>> it = students.entrySet().iterator();


while (it.hasNext()) {
Map.Entry<String, Student> e = it.next();
Student s =e.getValue();

if (s.getMarks()<marks) {

it.remove();

}
for (Student f : students.values())
System.out.println(f);

}
Day 14
package com.app.core;

public abstract class Emp {


private double basic;

public Emp(double basic) {


super();
this.basic = basic;
}

public double getBasic() {


return basic;
}

public abstract double computeSalary();

@Override
public String toString() {
return "Emp [basic=" + basic + "]";
}
}

package com.app.core;

public class HRMgr extends Mgr {

public HRMgr(double basic) {


super(basic);
// TODO Auto-generated constructor stub
}

@Override
public double computeSalary() {
// TODO Auto-generated method stub
return getBasic()+3000;
}

}
package com.app.core;

public class Mgr extends Emp {

public Mgr(double basic) {


super(basic);
// TODO Auto-generated constructor stub
}

@Override
public double computeSalary() {
// TODO Auto-generated method stub
return getBasic()+ 1000;
}
}

package com.app.core;

public class PermanentWorker extends Worker {

public PermanentWorker(double basic) {


super(basic);
// TODO Auto-generated constructor stub
}

@Override
public double computeSalary() {
// TODO Auto-generated method stub
return getBasic()+ 700;
}

package com.app.core;

public class SalesMgr extends Mgr {

public SalesMgr(double basic) {


super(basic);
// TODO Auto-generated constructor stub
}

@Override
public double computeSalary() {
// TODO Auto-generated method stub
return getBasic()+ 2000;
}

package com.app.core;

public class TempWorker extends Worker {

public TempWorker(double basic) {


super(basic);
// TODO Auto-generated constructor stub
}

@Override
public double computeSalary() {
// TODO Auto-generated method stub
return getBasic()+ 600;
}

package com.app.core;

public class Worker extends Emp {

public Worker(double basic) {


super(basic);
// TODO Auto-generated constructor stub
}

@Override
public double computeSalary() {
// TODO Auto-generated method stub
return getBasic() + 500;
}
}

package com.app.utils;

import java.util.ArrayList;
import java.util.List;
import com.app.core.Emp;

public interface GenericUtils {


/*
* write a static method in GenericUtils i/f
* -package : com.app.utils
to return sum of salaries of all emps from the specified list.
*/
// static double computeSum(List<? extends Emp> emps)
// {
// double sum=0.0;
// for(Emp e : emps)
// sum += e.computeSalary();
// return sum;
// }
static <T extends Emp> double computeSum(List<T> emps)
{
double sum=0.0;
for(Emp e : emps)
sum += e.computeSalary();
return sum;
}
static <T extends Comparable<? super T>> T findMax(List<T> list)
{//T must implement comparable i/f
//type of comparable must be either T or any of its super type
//chronolocalDate
//LocalDate-implementation class
T max=list.get(0);
for(T i: list) {
if(i.compareTo(max)>0) {
max=i;
}
}
return max;
}

package com.app.tester;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;

import com.app.core.Mgr;
import com.app.core.SalesMgr;
import com.app.core.TempWorker;
import com.app.utils.GenericUtils;

/*
* 1. Consider Emp inheritance hierarchy
write a static method in GenericUtils i/f -package : com.app.utils
to return sum of salaries of all emps from the specified list.
Test cases -- AL<Mgr> , Vector<TempWorker> ,
LinkedList<SalesMgr>

*/
public class Test1 {

public static void main(String[] args) {


ArrayList<Mgr> mgrs=new ArrayList<Mgr>(
List.of(new Mgr(1000), new Mgr(1500), new Mgr(2000)));
//call the method - computeSum
System.out.println(GenericUtils.computeSum(mgrs));
Vector<TempWorker> tempWorkers=new Vector<>(
Arrays.asList(new TempWorker(100),
new TempWorker(200),
new TempWorker(300)));
//call the method - computeSum
System.out.println(GenericUtils.computeSum(tempWorkers));
LinkedList<SalesMgr> salesMgrs=new LinkedList<>(
List.of(new SalesMgr(3000),
new SalesMgr(4000),
new SalesMgr(5000)));
//call the method - computeSum
System.out.println(GenericUtils.computeSum(salesMgrs));
}

}
package com.app.tester;

import static java.time.LocalDate.parse;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Vector;

import com.app.utils.GenericUtils;

/*
* 2. Solve - Write a generic method to return max element
* from ANY List
eg - Test cases
ArrayList<Integer>
LinkedList<Double>
Vector<LocalDate>

*/
public class Test2 {

public static void main(String[] args) {


ArrayList<Integer> ints=
new ArrayList<>(Arrays.asList(10,20,1,34,45,-70,59));
System.out.println("Max int "+GenericUtils.findMax(ints));
LinkedList<Double> doubles=
new LinkedList<>(Arrays.asList(10.0,20.6,1.3,3.4,
45.6,-70.77,59.0));
System.out.println("Max double "+GenericUtils.findMax(doubles));

Vector<LocalDate> dates=
new Vector<>(Arrays.asList(parse("2025-10-20"),
parse("2024-11-20"),
parse("2022-09-25"),
parse("2024-11-29"),
parse("2025-03-20")
));
System.out.println("Max Date (Latest Date) "+GenericUtils.findMax(dates));

package com.app.tester;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
import javax.swing.plaf.synth.SynthOptionPaneUI;

import com.app.core.Mgr;
import com.app.core.SalesMgr;
import com.app.core.TempWorker;

/*
* 3. Refer to Emp based organization hierarchy
Sort the emps as per their basic salary - must use Custom ordering
eg Test cases
AL | LinkedList | Vector of data type - Emp , Mgr , Worker or PermanentWorker , or
SalesMgr .....

*/
public class Test3 {

public static void main(String[] args) {


ArrayList<Mgr> mgrs=new ArrayList<Mgr>(
List.of(new Mgr(6000), new Mgr(1900), new Mgr(2000)));
Collections.sort(mgrs,new Comparator<Mgr>() {

@Override
public int compare(Mgr o1, Mgr o2) {
return ((Double)o1.getBasic()).compareTo(o2.getBasic());
}

});
System.out.println(mgrs);

Vector<TempWorker> tempWorkers=new Vector<>(


Arrays.asList(new TempWorker(1000),
new TempWorker(800),
new TempWorker(500),
new TempWorker(700)));
Collections.sort(tempWorkers,new Comparator<TempWorker>() {

@Override
public int compare(TempWorker o1, TempWorker o2) {

return ((Double)o1.getBasic()).compareTo(o2.getBasic());
}
});
System.out.println(tempWorkers);
LinkedList<SalesMgr> salesMgrs=new LinkedList<>(
List.of(new SalesMgr(3800),
new SalesMgr(4100),
new SalesMgr(4000)));
Collections.sort(salesMgrs,new Comparator<SalesMgr>() {

@Override
public int compare(SalesMgr o1, SalesMgr o2) {

return ((Double)o1.getBasic()).compareTo(o2.getBasic());
}

});
System.out.println(salesMgrs);

Day 16
package com.app.core;

import java.time.LocalDate;

public class Student{

private String rollNo;


private String name;
private LocalDate dob;
private Subject subject;
private double gpa;
private Address address;

public Student(String rollNo, String name, LocalDate dob, Subject subject, double gpa) {
super();
this.rollNo = rollNo;
this.name = name;
this.dob = dob;
this.subject = subject;
this.gpa = gpa;
}

@Override
public String toString() {
return "Student rollNo=" + rollNo + ", name=" + name + ", dob=" + dob + ",
subject=" + subject + ", gpa=" + gpa
+ " adr : " + address;
}

public String getRollNo() {


return rollNo;
}

public String getName() {


return name;
}

public LocalDate getDob() {


return dob;
}

public Subject getSubject() {


return subject;
}
public Address getAddress() {
return address;
}

public double getGpa() {


return gpa;
}

public void assignAddress(Address a) {


address = a;
}

package com.app.core;

public class Address {

private String city, state, phoneNo;

public Address(String city, String state, String phoneNo) {


super();
this.city = city;
this.state = state;
this.phoneNo = phoneNo;
}

@Override
public String toString() {
return "Address [city=" + city + ", state=" + state + ", phoneNo=" + phoneNo + "]";
}

public String getCity() {


return city;
}

public String getState() {


return state;
}

public String getPhoneNo() {


return phoneNo;
}

package com.app.core;

public enum Subject {


JAVA, PYTHON, DBT, REACT, ANGULAR, SE
}

package custom_exception;

public class StudentCollectionException extends Exception {

public StudentCollectionException(String message) {


super(message);
}

package utils;

import static com.app.core.Subject.DBT;


import static com.app.core.Subject.JAVA;
import static com.app.core.Subject.REACT;
import static com.app.core.Subject.ANGULAR;
import static java.time.LocalDate.parse;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.app.core.Address;
import com.app.core.Student;

public class StudentCollectionUtils {


private static int index = 0;

public static List<Student> populateList() {


List<Student> students = new ArrayList<>(
Arrays.asList(new Student("dac-001", "ravi", parse("1999-12-13"),
ANGULAR, 3.2),
new Student("dac-009", "riya", parse("1998-12-
13"), REACT, 6.9),
new Student("dac-004", "shekhar", parse("1997-12-
13"), DBT, 8.9),
new Student("dac-002", "priya", parse("1999-02-
23"), JAVA, 4.7),
new Student("dac-007", "kiran", parse("1996-02-
13"), DBT, 8.1),
new Student("dac-003", "meeta", parse("1998-12-
19"), DBT, 7.9),
new Student("dac-008", "sameer", parse("1997-12-
06"), JAVA, 8.2)));
List<Address> adrs = Arrays.asList(new Address("pune", "MH", "452446"), new
Address("pune", "MH", "652446"),
new Address("nagpur", "MH", "852446"), new Address("indore",
"MP", "752446"),
new Address("mumbai", "MH", "672446"), new Address("pune",
"MH", "692446"),
new Address("chennai", "TN", "862446"));

students.forEach(s -> s.assignAddress(adrs.get(index++)));


return students;// rets populated growable list of students with adr
}

// add a static method to accept list of student details & rets a map populated with the
same
public static Map<String, Student> populateMap(List<Student> list) {
HashMap<String, Student> hm = new HashMap<>();
list.forEach(s -> hm.put(s.getRollNo(), s));
return hm;

package tester;
import static utils.StudentCollectionUtils.populateList;
import static utils.StudentCollectionUtils.populateMap;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;

import com.app.core.Student;
import com.app.core.Subject;

import custom_exception.StudentCollectionException;
public class Test {

public static void main(String[] args) {


try(Scanner sc = new Scanner(System.in)) {
//3.0 Display all student details from the student map.
Map<String, Student> stmap = populateMap(populateList());
stmap.forEach((k,v)-> System.out.println(k+" " +v));

//3.1 Display details of the students who have taken a specified subject
// System.out.println("enter the subject");
// Subject sb= Subject.valueOf(sc.next().toUpperCase());
// stmap.values()
// .stream()
// .filter(p -> p.getSubject()==sb)
// .forEach(p -> System.out.println(p));

// 3.2 Print sum of marks of students of all students from the specified state
// i/p : name of the state
// System.out.println("enter the state");
// String st=sc.next().toUpperCase();
// double sum = stmap.values()
// .stream()
// .filter(p->p.getAddress().getState().equals(st))
// .mapToDouble(p->p.getGpa())
// .sum();
// System.out.println(sum);

//3.3 Print name of specified subject topper


// i/p : subject name
// System.out.println("enter the subject");
// Subject sb= Subject.valueOf(sc.next().toUpperCase());
// Student student = stmap.values()
// .stream()
// .filter(p->p.getSubject()==sb)
// .max((s1, s2) -> Double.compare(s1.getGpa(), s2.getGpa()))
// .orElseThrow(()-> new StudentCollectionException("not found"));
// System.out.println(student.getName());

// 3.4 Print no of failures for the specified subject chosen from user.
// i/p : subject name
// (failure is GPA < 5.0 , out of 1-10)
//

// 3.5 Display names of students enrolled in a specified subject , securing marks >
specified marks
// i/p : subject name , marks
// System.out.println("enter the subject and marks");
// Subject sb= Subject.valueOf(sc.next().toUpperCase());
// double gpa=sc.nextDouble();
//
// stmap.values()
// .stream()
// .filter(p -> p.getGpa()>gpa && p.getSubject()==sb)
// .forEach(p->System.out.println(p.getName()));

// 3.6 Suppose a subject faculty is unavailable n then subject is cancelled . Collect


the specified subject students into the list n display it.
// i/p : subject name
// System.out.println("enter the subject");
// Subject sb= Subject.valueOf(sc.next().toUpperCase());
// List<Student> collect = stmap.values()
// .stream()
// .filter(p-> p.getSubject()==sb)
// .collect(Collectors.toList());
//
// collect.forEach(p->System.out.println(p));

// 3.7 Display student details for specified subject , sorted as per DoB
System.out.println("enter the subject");
Subject sb= Subject.valueOf(sc.next().toUpperCase());
Comparator< Student> c=(p1,p2)->p1.getDob().compareTo(p2.getDob());
stmap.values()
.stream()
.filter(p->p.getSubject()==sb)
.sorted(c)
.forEach(p->System.out.println(p));

}catch (Exception e) {
System.out.println(e.getMessage());
}

Day 18
package com.app.core;

import java.time.LocalDate;

public class Student {


private String rollNo;
private String name;
private LocalDate dob;
private Subject subject;
private double gpa;
private Address address;
public Student(String rollNo, String name, LocalDate dob, Subject subject, double gpa) {
super();
this.rollNo = rollNo;
this.name = name;
this.dob = dob;
this.subject = subject;
this.gpa = gpa;
}
@Override
public String toString() {
return "Student rollNo=" + rollNo + ", name=" + name + ", dob=" + dob + ",
subject=" + subject
+ ", gpa=" + gpa
+ "adr : "+address;
}
public String getRollNo() {
return rollNo;
}
public String getName() {
return name;
}
public LocalDate getDob() {
return dob;
}
public Subject getSubject() {
return subject;
}
public double getGpa() {
return gpa;
}
public void assignAddress(Address a)
{
this.address=a;
}
public Address getAddress() {
return address;
}

package com.app.core;

public class Address {


private String city, state, phoneNo;

public Address(String city, String state, String phoneNo) {


super();
this.city = city;
this.state = state;
this.phoneNo = phoneNo;
}

@Override
public String toString() {
return "Address [city=" + city + ", state=" + state + ", phoneNo=" + phoneNo + "]";
}

public String getCity() {


return city;
}

public String getState() {


return state;
}

public String getPhoneNo() {


return phoneNo;
}

package com.app.core;
public enum Subject {
JAVA, R, ML, CLOUD, PYTHON, DBT
}

package com.app.utils;

import static com.app.core.Subject.DBT;


import static com.app.core.Subject.JAVA;
import static com.app.core.Subject.ML;
import static com.app.core.Subject.R;
import static java.time.LocalDate.parse;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.stream.Collector;
import java.util.stream.Collectors;

import com.app.core.Address;
import com.app.core.Student;

public class StudentCollectionUtils {


private static int index;
public static List<Student> populateList() {
List<Student> students = Arrays.asList(new Student("dac-001", "ravi",
parse("1990-12-13"), DBT, 7),
new Student("dac-009", "riya", parse("1992-12-13"), ML, 6.9),
new Student("dac-004", "shekhar", parse("1991-12-13"), DBT,
8.9),
new Student("dac-002", "priya", parse("1990-02-23"), JAVA, 4),
new Student("dac-007", "kiran", parse("1993-02-13"), R, 8.9),
new Student("dac-003", "meeta", parse("1993-12-13"), R, 5.9),
new Student("dac-008", "sameer", parse("1991-12-06"), DBT, 5));
List<Address> adrs = Arrays.asList(new Address("pune", "MH", "452446"), new
Address("pune", "MH", "652446"),
new Address("nagpur", "MH", "852446"), new Address("indore",
"MP", "752446"),
new Address("mumbai", "MH", "672446"), new Address("pune",
"MH", "692446"),
new Address("chennai", "TN", "862446"));

// for (Student s : students)


// s.assignAddress(adrs.get(index++));
students.forEach(s -> s.assignAddress(adrs.get(index++)));// index++ make a
wrong effect refer readme

// somewhere in day 18
return students;// fixed size student list , where students are linked with address.

}
public static Map<String, Student> populatedMap(){
List<Student> st=populateList();
// Map<String, Student> map=new HashMap<>();
// Map<String, Student>map = st.stream().collect(Collectors.toMap(i-
>i.getRollNo(),i->i));
// st.forEach(i->map.put(i.getRollNo(), i));
return st.stream().collect(Collectors.toMap(i->i.getRollNo(),i->i));

}
}

package threads;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Comparator;
import java.util.Map;

import com.app.core.Student;

public class SortByDOB implements Runnable {


private String fileName;
private Map<String, Student> map;

public SortByDOB(String name, Map<String, Student> map) {


fileName = name;
this.map = map;
System.out.println("in ctor of " + Thread.currentThread().getName());
}

@Override
public void run() {
System.out.println("In run method of"+ Thread.currentThread().getName()+"is
started");
try (PrintWriter pw = new PrintWriter(new FileWriter(fileName))) {
Comparator<Student> c = (p1, p2) ->
p1.getDob().compareTo(p2.getDob());
map.values().stream().sorted(c).forEach(i -> pw.println(i));
} catch (IOException e) {
System.out.println("catch of "+Thread.currentThread().getName()
+e.getMessage());
}
System.out.println("In run method of"+ Thread.currentThread().getName()+"is
over");
}
}

package threads;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Comparator;
import java.util.Map;

import com.app.core.Student;

public class SortBynameNGpa implements Runnable {


private String fileName;
private Map<String, Student> map;

public SortBynameNGpa(String name, Map<String, Student> map) {


fileName = name;
this.map = map;
System.out.println("in ctor of " + Thread.currentThread().getName());
}

@Override
public void run() {
System.out.println("In run method of"+ Thread.currentThread().getName()+"is
started");
try (PrintWriter pw = new PrintWriter(new FileWriter(fileName))) {
Comparator<Student> c = (p1, p2) -> {
int
val=p1.getSubject().name() .compareTo(p2.getSubject().name());
if(val==0) {
return ((Double)p1.getGpa()).compareTo(p2.getGpa());
}
return val;
};
map.values().stream().sorted(c).forEach(i -> pw.println(i));
} catch (IOException e) {
System.out.println("in catch of"+Thread.currentThread().getName()
+e.getMessage());
}
System.out.println("In run method of"+ Thread.currentThread().getName()+"is
over");

package threads;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Comparator;
import java.util.Map;

import com.app.core.Student;

public class StoreRollNNameNGpa implements Runnable {


private String fileName;
private Map<String, Student> map;
private String city;

public StoreRollNNameNGpa(String name, Map<String, Student> map,String city) {


fileName = name;
this.map = map;
this.city=city;
System.out.println("in ctor of " + Thread.currentThread().getName());
}

@Override
public void run() {
System.out.println("In run method of"+ Thread.currentThread().getName()+"is
started");
try (PrintWriter pw = new PrintWriter(new FileWriter(fileName))) {
Comparator< Student> c=(p1,p2)-
>((Double)p2.getGpa()).compareTo(p1.getGpa());
map.values().stream().filter(i-
>i.getAddress().getCity().equals(city)).sorted(c).forEach(i-> pw.println(i.getRollNo()+"
"+i.getName()+" "+i.getGpa()));

} catch (IOException e) {
System.out.println("in catch of"+Thread.currentThread().getName()
+e.getMessage());
}
System.out.println("In run method of"+ Thread.currentThread().getName()+"is
over");

}
}

package threads;

import java.util.Map;
import java.util.Scanner;

import com.app.core.Student;

import static com.app.utils.StudentCollectionUtils.*;


public class Tester {

public static void main(String[] args) {


try(Scanner sc = new Scanner(System.in);){
Map<String , Student> students=populatedMap();
System.out.println("Enter the 3 file name and city");
String a=sc.next();
String b=sc.next();
String c=sc.next();
String city=sc.next();
Thread t1=new Thread(new SortByDOB(a, students));
Thread t2=new Thread(new SortBynameNGpa(b, students));
Thread t3=new Thread(new StoreRollNNameNGpa(c, students,city));
t1.start();
t2.start();
t3.start();

System.out.println(t1.isAlive()+" "+t2.isAlive()+" "+t3.isAlive());


System.out.println("main wait for chile thread to over");
t1.join();
t2.join();
t3.join();

}
catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println("main is over");

You might also like