Skip to content

Instantly share code, notes, and snippets.

@sandeepmchouhan111293
Created January 21, 2017 10:01
Show Gist options
  • Save sandeepmchouhan111293/7600c954a9737ea898ca6353b352c14b to your computer and use it in GitHub Desktop.
Save sandeepmchouhan111293/7600c954a9737ea898ca6353b352c14b to your computer and use it in GitHub Desktop.
3.1)
=====
import java.util.Scanner;
public class StringOperations {
String str = new String();
public StringOperations(String str){
this.str=str;
}
public void stringOperation(){
int ch;
String choice;
Scanner in = new Scanner(System.in);
//System.out.println(ch);
//System.exit(0);
do
{
System.out.println("1.Concatenate string");
System.out.println("2.Replace odd positions with #");
System.out.println("3.Remove duplicate characters");
System.out.println("4.Change odd characters to upper string");
int i=0;
System.out.println("Enter your choice");
ch = in.nextInt();
switch(ch)
{
case 1:
//System.out.println("Enter string1");
//String str1 =in.next();
String res = str.concat(str);
System.out.println("Result :"+res);
break;
case 2:
System.out.println("Enter a string");
//String str = in.next();
int len = str.length();
String res1 = "";
char ch2;
//System.out.println(len);
for(i=0;i<len;++i){
ch2 = str.charAt(i);
//System.out.println(i);
if(i%2!=0)
{
//System.out.println("here");
ch2 = '#';
}
res1+=ch2;
}
System.out.println("Result: "+res1);
break;
case 3:
//System.out.println("Enter a string");
i=0;
int j=0;
//String str4 = in.next();
res ="";
for(i=0;i<str.length();++i)
{
char ch1 = str.charAt(i);
for(j=i+1;j<str.length();++j)
{
if(ch1==str.charAt(j)){
//str4 = str4.replace('t'/*str4.charAt(j)*/, '\0');
ch1 = ' ';
}
}
res += ch1;
}
res= res.trim();
res = res.replaceAll("\\s","");
System.out.println(res);
break;
case 4:
//System.out.println("Enter a string");
//String str5 = in.next();
String res2="";
i=0;
//String stringtemp="";
for(i=0;i<str.length();++i){
char ch3 = str.charAt(i);
if(i%2!=0&&ch3>96&&ch3<123){
ch3 = (char)(ch3-32);
}
res2+=ch3;
}
System.out.println("Result :"+res2);
}
System.out.println("Do you wish to perform more operations: Yes/No?");
choice = in.next();
}while(choice.equalsIgnoreCase("Yes"));
}
}
============================================================================
3.2)
======
public class StringTest {
String str = new String();
public StringTest(String str) {
super();
this.str = str;
}
public void stringPositive()
{
int i=0;
int flag=1;
//System.out.println(str.length());
int len = str.length();
//char[] s = str.toCharArray();
//String str = new String();
while(i<len - 1)
{
//System.out.println("INSIDE LOOP");
if(str.charAt(i)>str.charAt(i+1)){
flag = 0;
break;
}
//System.out.println(i);
i = i + 1;
}
if(flag == 1)
{
System.out.println("Positive");
}
else
{
System.out.println("Negative");
}
}
}
======================================================================
import java.util.Scanner;
import java.io.*;
public class TestString {
public static void main(String[] args)throws IOException {
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
String str = in.next();
//char[] ch = new char[100];
StringTest st = new StringTest(str);
//System.out.println("input taken");
st.stringPositive();
}
}
============================================================================
3.3)
=====
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
public class DateDuration {
public void showDate() {
//Date date = new Date();
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy");
Scanner in = new Scanner(System.in);
System.out.println("Enter a date");
String textdate =in.next();
//System.out.println(textdate);
LocalDate date = LocalDate.parse(textdate,format);
LocalDate todayDate = LocalDate.now();
Period period = date.until(todayDate);
//final ZonedDateTime parsed = ZonedDateTime.parse(textdate,format.withZone(ZoneId.of("UTC")));
System.out.println("Days Duration :"+period.getDays());
System.out.println("Months Duration :"+period.getMonths());
System.out.println("Years Duration :"+period.getYears());
}
}
===================================================================================================================
3.4)
====
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.Date;
public class TwoDatesDuration {
String date1,date2;
public TwoDatesDuration(String date1, String date2) {
super();
this.date1 = date1;
this.date2 = date2;
}
public void datesDuration(){
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate date = LocalDate.parse(date1,format);
LocalDate anotherdate = LocalDate.parse(date2,format);
Period period = date.until(anotherdate);
//LocalDate newdate = LocalDate.parse(text,format);
//System.out.println(newdate);
System.out.println("Days Duration :"+period.getDays());
System.out.println("Months Duration :"+period.getMonths());
System.out.println("Years Duration :"+period.getYears());
}
}
===========
import java.util.Scanner;
public class TwoDatesInput {
public void datesInput(){
Scanner in = new Scanner(System.in);
System.out.println("Enter date1");
String date1 = in.next();
System.out.println("Enter date2");
String date2 = in.next();
TwoDatesDuration date = new TwoDatesDuration(date1,date2);
date.datesDuration();
}
}
==========================================================================================
3.5)
=======
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
public class ProductDateExpiry {
String purchasedate;
public ProductDateExpiry(String purchasedate) {
super();
this.purchasedate = purchasedate;
}
public ProductDateExpiry() {
super();
}
public void showExpiryDate(int months,int years){
int remmonths,remyears;
String text;
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate date = LocalDate.parse(purchasedate,format);
//System.out.println(date);
if(months>12)
{
remmonths = months%12;
remyears = months/12+years;
//text = format.format((date.(remmonths)));
//text = format.format(date.plusYears(remyears));
}
else
{
remmonths = months;
remyears = years;
//text = format.format((date.plusMonths(remmonths)));
//text = format.format(date.plusYears(remyears));
}
text = format.format((date.plusMonths(remmonths)));
text = format.format(date.plusYears(remyears));
System.out.println("Expiry Date of the Product :"+text);
}
}
==================================================================================
import java.util.Scanner;
public class ProductExpiryRange {
public void acceptExpiryLimit(){
Scanner in = new Scanner(System.in);
System.out.println("Enter product purchase date");
String date = in.next();
ProductDateExpiry purchasedate = new ProductDateExpiry(date);
System.out.println("Enter months range");
int months = in.nextInt();
System.out.println("Enter years range");
int years = in.nextInt();
//ProductDateExpiry range = new ProductDateExpiry();
purchasedate.showExpiryDate(months,years);
}
}
===================================================================================
3.6)
=====
import java.util.Scanner;
public class AcceptZoneId {
public void takeZoneId(){
Scanner in =new Scanner(System.in);
System.out.println("Enter zoneid");
String zoneid = in.next();
TimeZone zone = new TimeZone(zoneid);
zone.showZonedTime();
}
}
=============
3.7 a)
======
import java.util.Date;
import java.util.Scanner;
public class CalculateAge {
public int calage(){
Scanner in = new Scanner(System.in);
System.out.println("Enter date of birth");
String dob = in.next();
Date date1 = new Date(dob);
Date today = new Date();
int age = today.getYear() - date1.getYear();
return age;
}
}
3.7 b)
======
public class FullName
{
public String getFullName(String firstName,String lastName)
{
return (firstName+' '+lastName);
}
public static void main(String[] args)
{
Scanner object =new Scanner(System.in);
System.out.println("Enter Your First Name:");
String fname=object.next();
System.out.println("Enter Your Last Name:");
String lname=object.next();
String fullname=getFullName(fname,lname);
System.out.println("Full Name:"+fullname);
}
}
=========================================================================
LAB 4
========
4.1
=========
Account Class
=============
//Sandeep Chouhan
public class Account
{
private long accNum;
private double balance;
private Person accHolder;
public Account(long accNum, double balance, Person accHolder)
{
super();
this.accNum = accNum;
this.balance = balance;
this.accHolder = accHolder;
}
public long getAccNum()
{
return accNum;
}
public void setAccNum(long accNum)
{
this.accNum = accNum;
}
public Person getAccHolder()
{
return accHolder;
}
public void setAccHolder(Person accHolder)
{
this.accHolder = accHolder;
}
public void setBalance(double balance)
{
this.balance = balance;
}
public void deposit(double amount)
{
balance+=amount;
}
public void withdraw(double amount)
{
balance-=amount;
}
public void getBalance()
{
System.out.println(balance);
}
@Override
public String toString()
{
return "Account [accNum=" + accNum + ", balance=" + balance
+ ", accHolder=" + accHolder + "]";
}
}
================================================================================================
public class AccountMain
{
public static void main(String[] args)
{
Person smith = new Person("Smith",23);
Person kathy = new Person("Kathy",31);
AtomicInteger count = new AtomicInteger(0);
Account smithaccount = new Account(count.incrementAndGet(),2000,smith);
Account kathyaccount = new Account(count.incrementAndGet(),3000,kathy);
System.out.println(smithaccount);
System.out.println(kathyaccount);
smithaccount.deposit(2000);
kathyaccount.withdraw(2000);
System.out.println("Balance in Smith's Account:");
smithaccount.getBalance();
System.out.println("Balance in Kathy's Account:");
kathyaccount.getBalance();
}
}
=================================================================================================+
package com.capgemini.services;
public class SavingsAccount extends AccountAbstract {
final double minbal = 500;
double bal = getBalance();
public SavingsAccount(long accNum, double balance, Person accHolder) {
super(accNum, balance, accHolder);
// TODO Auto-generated constructor stub
}
@Override
public void deposit(double amount) {
bal+=amount;
System.out.println("Balance updated :"+bal);
}
@Override
public void withdraw(double amount) {
if(bal - amount<minbal){
System.out.println("Ammount cannot be withdrawn due to minimum balance issue");
}
else{
bal-=amount;
}
}
/*public String toString() {
return "SavingsAccount [accNum=" + accNum + ", balance=" + balance
+ ", accHolder=" + accHolder + "]";
}*/
}
======================================================================
package com.capgemini.services;
public class CurrentAccount extends AccountAbstract {
boolean flag=true;
double bal = getBalance();
double overdraftlimit=-1;
public CurrentAccount(long accNum, double balance, Person accHolder) {
super(accNum, balance, accHolder);
// TODO Auto-generated constructor stub
}
@Override
public void deposit(double amount) {
bal+=amount;
}
@Override
public void withdraw(double amount) {
if(bal - amount<=overdraftlimit){
System.out.println("Overdraft limit reached: amount cannot be withdrawn");
}
else
{
bal-=amount;
}
}
public void getaccountBalance(){
System.out.println(bal);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
/*@Override
public String toString() {
return "CurrentAccount [accNum=" + accNum + ", balance=" + balance
+ ", accHolder=" + accHolder + "]";
}*/
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
}
======================================================================
package com.capgemini.services;
public class AccountAbstract {
private long accNum;
private double balance;
private Person accHolder;
public AccountAbstract(long accNum, double balance, Person accHolder) {
super();
this.accNum = accNum;
this.balance = balance;
this.accHolder = accHolder;
}
/**
* @return the accNum
*/
public long getAccNum() {
return accNum;
}
public void setAccNum(long accNum) {
this.accNum = accNum;
}
public Person getAccHolder() {
return accHolder;
}
public void setAccHolder(Person accHolder) {
this.accHolder = accHolder;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public void deposit(double amount){
balance+=amount;
}
public void withdraw(double amount){
balance-=amount;
}
public void getaccountBalance(){
System.out.println(balance);
}
@Override
public String toString() {
return "Account [accNum=" + accNum + ", balance=" + balance
+ ", accHolder=" + accHolder + "]";
}
}
=============================================================================
package com.capgemini.services;
public class Person
{
private String name;
private int age;
public Person(String name, int age)
{
super();
this.name = name;
this.age = age;
}
public Person()
{
super();
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
@Override
public String toString()
{
return "Person [name=" + name + ", age=" + age + "]";
}
}
=============================================================================
package com.cg.eis.bean;
public class Employee {
public int id;
public String name,designation,insuranceScheme;
public double salary;
public Employee(int id, String name, String designation,String insuranceScheme,double salary) {
super();
this.id = id;
this.name = name;
this.designation = designation;
this.insuranceScheme = insuranceScheme;
this.salary = salary;
}
public Employee(){
}
}
=========================================================================================================
package com.cg.eis.service;
import com.cg.eis.bean.Employee;
public interface EmployeeService {
public Employee getEmpDetails();
public String insuranceScheme(String designation,double Salary);
public void EmpDetails(Employee emp);
}
=========================================================================================================
package com.cg.eis.pl;
import java.util.Scanner;
import com.cg.eis.bean.Employee;
import com.cg.eis.service.EmployeeService;
public class EmployeeServiceImpl implements EmployeeService {
@Override
public Employee getEmpDetails() {
String designation;
String insuranceScheme = null;
Scanner in = new Scanner(System.in);
System.out.println("Enter employee id");
int id = in.nextInt();
System.out.println("Enter employee salary");
double salary = in.nextDouble();
System.out.println("Enter employee name");
String name = in.next();
if(salary<5000){
designation = "Clerk";
}
else if(salary>5000&&salary<20000){
designation = "System Associate";
}
else if(salary>=20000&&salary<40000){
designation = "Programmer";
}
else{
designation = "Manager";
}
Employee emp = new Employee(id,name,designation,insuranceScheme,salary);
return emp;
}
@Override
public String insuranceScheme(String designation,double salary) {
String scheme;
if(designation == "Clerk")
scheme = "No Scheme";
else if(designation == "System Associate")
scheme = "Scheme C";
else if(designation == "Programmer")
scheme = "Scheme B";
else
scheme = "Scheme A";
return scheme;
}
@Override
public void EmpDetails(Employee emp) {
System.out.println("Employee id"+emp.id);
System.out.println("Employee name"+emp.name);
System.out.println("Employee designation"+emp.designation);
System.out.println("Employee salary"+emp.salary);
System.out.println("Employee insurancescheme"+emp.insuranceScheme);
}
}
==========================================================================================================
package com.cg.eis.pl;
import com.cg.eis.bean.Employee;
public class EmployeeMain {
public static void main(String[] args) {
EmployeeServiceImpl emp = new EmployeeServiceImpl();
Employee emp1 = emp.getEmpDetails();
String scheme = emp.insuranceScheme(emp1.designation, emp1.salary);
Employee person = new Employee(emp1.id,emp1.name,emp1.designation,scheme,emp1.salary);
//System.out.println(emp1.name);
//emp.insuranceScheme();
emp.EmpDetails(person);
}
}
package com.capgemini.exception;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class AcceptEmployeeInput {
Scanner in = new Scanner(System.in);
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
public void acceptInput() throws IOException{
/*System.out.println(("Displayiing details through parameterized contructor"));
System.out.println("First Name : "+fname);
System.out.println("Last Name : "+lname);
System.out.println("Gender : "+gender);*/
try {
//person.setFirstName(fname);
System.out.println("Enter first name");
String fname = b.readLine();
if(fname.equals(""))
throw new NameException("Employee Name is null");
System.out.println("Enter last name");
String lname = b.readLine();
if(lname.equals("")){
throw new NameException("Employee Name is null");
}
//String fullName = fname + lname;
else{
System.out.println("Enter gender");
char gender = (char)System.in.read();
EmployeeNameException person = new EmployeeNameException(fname,lname,gender);
fname = person.getFirstName();
//person.setLastName(lname);
lname=person.getLastName();
gender=person.getGender();
//System.out.println("Displaying details through getter method");
System.out.println("First Name : "+fname);
System.out.println("Last Name : "+lname);
System.out.println("Gender : "+gender);
}
} catch (NameException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
}
//person.setGender(gender);
//gender=person.getGender();
}
}
=============================================================================================================
package com.capgemini.exception;
public class AccountAbstract {
private long accNum;
private double balance;
private Person accHolder;
public AccountAbstract(long accNum, double balance, Person accHolder) {
super();
this.accNum = accNum;
this.balance = balance;
this.accHolder = accHolder;
}
/**
* @return the accNum
*/
public long getAccNum() {
return accNum;
}
/**
* @param accNum the accNum to set
*/
public void setAccNum(long accNum) {
this.accNum = accNum;
}
/**
* @return the accHolder
*/
public Person getAccHolder() {
return accHolder;
}
/**
* @param accHolder the accHolder to set
*/
public void setAccHolder(Person accHolder) {
this.accHolder = accHolder;
}
/**
* @param balance the balance to set
*/
/**
* @return the balance
*/
public double getBalance() {
return balance;
}
/**
* @param balance the balance to set
*/
public void setBalance(double balance) {
this.balance = balance;
}
public void deposit(double amount){
balance+=amount;
}
public void withdraw(double amount){
balance-=amount;
}
public void getaccountBalance(){
System.out.println(balance);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Account [accNum=" + accNum + ", balance=" + balance
+ ", accHolder=" + accHolder + "]";
}
}
=======================================================================================
package com.capgemini.exception;
public class AgeException extends Exception {
public AgeException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public AgeException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
}
=======================================================================================
package com.capgemini.exception;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger;
public class CheckAge {
public void ageCheck(){
AtomicInteger count = new AtomicInteger(0);
Scanner in = new Scanner(System.in);
try {
Person smith = new Person("Smith",21);
int age = smith.getAge();
if(age<15)
throw new AgeException(smith.getName()+"'s age is less than 15");
Person kathy = new Person("Kathy",31);
age = kathy.getAge();
if(age<15)
throw new AgeException(kathy.getName()+"'s age is less than 15");
AccountAbstract smithsavingaccount = new SavingsAccount(count.incrementAndGet(),2000,smith);
AccountAbstract smithcurrentaccount = new CurrentAccount(count.incrementAndGet(),2000,smith);
System.out.println(smithsavingaccount);
System.out.println(smithcurrentaccount);
System.out.println("For AccountHolder Smith :");
/*if(choice=="deposit"&&type=="savings"){*/
System.out.println("Enter amount to deposit in savingsaccount");
double amount = in.nextDouble();
smithsavingaccount.deposit(amount);
System.out.println("Enter amount to withdraw in savings account ");
amount = in.nextDouble();
smithsavingaccount.withdraw(amount);
System.out.println("Enter amount to deposit in currentaccount");
amount = in.nextDouble();
smithcurrentaccount.deposit(amount);
System.out.println("Enter amount to withdraw in currentaccount");
amount = in.nextDouble();
smithcurrentaccount.withdraw(amount);
//smithaccount.deposit(2000);
//kathyaccount.withdraw(2000);
System.out.println("Balance in Smith's Current Account:");
smithcurrentaccount.getaccountBalance();
System.out.println("Balance in Smith's Savings Account:");
smithsavingaccount.getaccountBalance();
AccountAbstract kathysavingaccount = new SavingsAccount(count.incrementAndGet(),3000,kathy);
AccountAbstract kathycurrentaccount = new CurrentAccount(count.incrementAndGet(),3000,kathy);
System.out.println(kathysavingaccount);
System.out.println(kathycurrentaccount);
//System.out.println(smithaccount);
//System.out.println(kathyaccount);
/*System.out.println("Enter type of operation to perform for :Smith");
String choice = in.next();
System.out.println("Enter the account type:");
String type = in.next();*/
System.out.println("For AccountHolder Kathy :");
/*if(choice=="deposit"&&type=="savings"){*/
System.out.println("Enter amount to deposit in savingsaccount");
amount = in.nextDouble();
kathysavingaccount.deposit(amount);
System.out.println("Enter amount to withdraw in savings account ");
amount = in.nextDouble();
kathysavingaccount.withdraw(amount);
System.out.println("Enter amount to deposit in currentaccount");
amount = in.nextDouble();
kathycurrentaccount.deposit(amount);
System.out.println("Enter amount to withdraw in currentaccount");
amount = in.nextDouble();
kathycurrentaccount.withdraw(amount);
//smithaccount.deposit(2000);
//kathyaccount.withdraw(2000);
System.out.println("Balance in Kathy's Current Account:");
kathycurrentaccount.getaccountBalance();
System.out.println("Balance in Kathy's Savings Account:");
kathysavingaccount.getaccountBalance();
//System.out.println("Balance in Kathy's Account:");
//kathyaccount.getBalance();
} catch (AgeException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
}
}
}
=============================================================================================
package com.capgemini.exception;
public class CurrentAccount extends AccountAbstract {
boolean flag=true;
double bal = getBalance();
double overdraftlimit=-1;
public CurrentAccount(long accNum, double balance, Person accHolder) {
super(accNum, balance, accHolder);
// TODO Auto-generated constructor stub
}
@Override
public void deposit(double amount) {
bal+=amount;
}
@Override
public void withdraw(double amount) {
if(bal - amount<=overdraftlimit){
System.out.println("Overdraft limit reached: amount cannot be withdrawn");
}
else
{
bal-=amount;
}
}
public void getaccountBalance(){
System.out.println(bal);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
/*@Override
public String toString() {
return "CurrentAccount [accNum=" + accNum + ", balance=" + balance
+ ", accHolder=" + accHolder + "]";
}*/
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
}
=====================================================================================
package com.capgemini.exception;
public class EmployeeNameException {
private String firstName="",lastName="";
private char gender=' ';
public EmployeeNameException() {
}
public EmployeeNameException(String firstName,String lastName,char gender){
this.firstName = firstName;
this.lastName = lastName;
this.gender = gender;
}
/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* @param firstName the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* @return the lastName
*/
public String getLastName() {
return lastName;
}
/**
* @param lastName the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* @return the gender
*/
public char getGender() {
return gender;
}
/**
* @param gender the gender to set
*/
public void setGender(char gender) {
this.gender = gender;
}
}
==========================================================================
package com.capgemini.exception;
public class NameException extends Exception {
public NameException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public NameException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
}
=================================================================================
package com.capgemini.exception;
public class Person {
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Person() {
super();
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
==========================================================================
package com.capgemini.exception;
public class SavingsAccount extends AccountAbstract {
final double minbal = 500;
double bal = getBalance();
public SavingsAccount(long accNum, double balance, Person accHolder) {
super(accNum, balance, accHolder);
// TODO Auto-generated constructor stub
}
@Override
public void deposit(double amount) {
bal+=amount;
System.out.println("Balance updated :"+bal);
}
@Override
public void withdraw(double amount) {
if(bal - amount<minbal){
System.out.println("Ammount cannot be withdrawn due to minimum balance issue");
}
else{
bal-=amount;
}
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
/*public String toString() {
return "SavingsAccount [accNum=" + accNum + ", balance=" + balance
+ ", accHolder=" + accHolder + "]";
}*/
}
========================================================================================================
package com.capgemini.test;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger;
import com.capgemini.exception.AccountAbstract;
import com.capgemini.exception.CurrentAccount;
import com.capgemini.exception.Person;
import com.capgemini.exception.SavingsAccount;
import com.capgemini.exception.CheckAge;
public class AgeExceptionTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
CheckAge check = new CheckAge();
check.ageCheck();
}
}
============================================================================
package com.capgemini.test;
import com.capgemini.exception.AcceptEmployeeInput;
import com.capgemini.exception.EmployeeNameException;
import java.util.Scanner;
import java.io.*;
public class EmployeeNameExceptionTest {
public static void main(String[] args) throws IOException{
AcceptEmployeeInput in = new AcceptEmployeeInput();
in.acceptInput();
}
}
===============================================================================
package com.cg.eis.bean;
public class Employee {
public int id;
public String name,designation,insuranceScheme;
public double salary;
public Employee(int id, String name, String designation,String insuranceScheme,double salary) {
super();
this.id = id;
this.name = name;
this.designation = designation;
this.insuranceScheme = insuranceScheme;
this.salary = salary;
}
public Employee(){
}
}
=======================================================================================================
package com.cg.eis.exception;
import com.cg.eis.bean.Employee;
import com.cg.eis.pl.EmployeeServiceImpl;
public class CheckException {
public void checkSalary(){
EmployeeServiceImpl emp = new EmployeeServiceImpl();
Employee emp1 = emp.getEmpDetails();
if(emp1.salary<3000){
//EmployeeException e = new EmployeeException(emp1.salary);
//e.catchEmployeeException();
double salary = emp1.salary;
try {
throw new EmployeeException("Salary less than 3000 :"+salary);
} catch (EmployeeException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
}
}
else{
String scheme = emp.insuranceScheme(emp1.designation, emp1.salary);
Employee person = new Employee(emp1.id,emp1.name,emp1.designation,scheme,emp1.salary);
emp.EmpDetails(person);
}
}
}
===========================================================================================================
package com.cg.eis.exception;
public class EmployeeException extends Exception {
double salary;
public EmployeeException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public EmployeeException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
/*public EmployeeException(double salary){
this.salary = salary;
}
public void catchEmployeeException(){
try{
throw new EmployeeException("Salary less than 3000 :"+salary);
}
catch(EmployeeException e){
System.out.println(e.getMessage());
}
}*/
}
========================================================================================
package com.cg.eis.pl;
import com.cg.eis.bean.Employee;
import com.cg.eis.exception.CheckException;
import com.cg.eis.exception.EmployeeException;
public class EmployeeMain {
public static void main(String[] args) {
CheckException check = new CheckException();
check.checkSalary();
//System.out.println(emp1.name);
//emp.insuranceScheme();
}
}
====================================================================
package com.cg.eis.pl;
import java.util.Scanner;
import com.cg.eis.bean.Employee;
import com.cg.eis.service.EmployeeService;
public class EmployeeServiceImpl implements EmployeeService {
@Override
public Employee getEmpDetails() {
String designation;
String insuranceScheme = null;
Scanner in = new Scanner(System.in);
System.out.println("Enter employee id");
int id = in.nextInt();
System.out.println("Enter employee salary");
double salary = in.nextDouble();
System.out.println("Enter employee name");
String name = in.next();
if(salary<5000){
designation = "Clerk";
}
else if(salary>5000&&salary<20000){
designation = "System Associate";
}
else if(salary>=20000&&salary<40000){
designation = "Programmer";
}
else{
designation = "Manager";
}
Employee emp = new Employee(id,name,designation,insuranceScheme,salary);
return emp;
}
@Override
public String insuranceScheme(String designation,double salary) {
String scheme;
if(designation == "Clerk")
scheme = "No Scheme";
else if(designation == "System Associate")
scheme = "Scheme C";
else if(designation == "Programmer")
scheme = "Scheme B";
else
scheme = "Scheme A";
return scheme;
}
@Override
public void EmpDetails(Employee emp) {
System.out.println("Employee id"+emp.id);
System.out.println("Employee name"+emp.name);
System.out.println("Employee designation"+emp.designation);
System.out.println("Employee salary"+emp.salary);
System.out.println("Employee insurancescheme"+emp.insuranceScheme);
}
}
======================================================================================
package com.cg.eis.service;
import com.cg.eis.bean.Employee;
public interface EmployeeService {
public Employee getEmpDetails();
public String insuranceScheme(String designation,double Salary);
public void EmpDetails(Employee emp);
}
package com.capgemini.services;
import java.util.ArrayList;
import java.util.Collections;
public class ArrayListProducts {
public static void main(String[] args) {
ArrayList<String> list=new ArrayList<String>();
list.add("Shirts");
list.add("Hoodies");
list.add("Trousers");
list.add("Ties");
System.out.println(list);
Collections.sort(list);
System.out.println(list);
}
}
======================================================================
package com.capgemini.services;
import java.util.ArrayList;
import java.util.Collections;
public class ArrayListProductsNew {
public static void main(String[] args) {
ArrayList<String> list=new ArrayList<String>();
list.add("Shirts");
list.add("Hoodies");
list.add("Trousers");
list.add("Ties");
//System.out.println(list);
Collections.sort(list);
for(String count:list){
System.out.println(list);
}
}
}
==================================================================
package assignment8.com.cg.operation;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
public class FileOperation {
public static void main(String[] args){
String filePath="D:\\Java Workspace\\Java Assignments\\src\\assignment8\\com\\cg\\data";
String fileName="Check.txt";
String fileName1="WriteCheck.txt";
try(FileReader fReader=new FileReader(filePath+"\\"+fileName);
BufferedReader bReader=new BufferedReader(fReader);
OutputStream writer=new FileOutputStream(filePath+"\\"+fileName1);
)
{
StringBuffer inputBuffer=new StringBuffer();
String strLine=bReader.readLine();
while(strLine!=null)
{
//System.out.println(strLine);
for(int i=0;i<strLine.length();i++)
inputBuffer.append(strLine.charAt(i));
inputBuffer.append("\n");
strLine=bReader.readLine();
}
inputBuffer=inputBuffer.reverse();
//System.out.println(inputBuffer);
int length=inputBuffer.length();
//System.out.println(length);
for(int i=0;i<length;i++){
writer.write(inputBuffer.charAt(i));
//System.out.println(inputBuffer.charAt(i));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
=========================================================================================
package assignment83;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScannerDelimiter {
public static void main(String[] args) {
String fPath="E:\\C++\\Java\\CoreJava\\src\\numbers.txt";
File file=new File(fPath);
try (Scanner input=new Scanner(file).useDelimiter("[,]");){
while(input.hasNext()){
int val=input.nextInt();
if(val%2==0)
System.out.println(val);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
========================================================================================
package assignment83.exception;
public class BlankNameException extends Exception {
private static final long serialVersionUID = 1L;
public BlankNameException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public BlankNameException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
}
====================================================================
package assignment83.exception;
public class EmployeeException extends Exception {
private static final long serialVersionUID = 1L;
public EmployeeException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public EmployeeException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
}
===========================================================================
package assignment83.exception;
public class UnderAgeException extends Exception {
private static final long serialVersionUID = 1L;
public UnderAgeException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public UnderAgeException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
}
===============================================================
package assignment83.com.cg.eis.bean;
import java.io.Serializable;
import assignment6.exception.EmployeeException;
import assignment6.com.cg.eis.service.EmployeeInsurance;
import assignment6.com.cg.eis.service.EmployeeService;
public class Employee implements Serializable{
private static final long serialVersionUID = 1L;
private int empId;
private String empName;
private double empSalary;
private String empDesign;
private String insuranceScheme;
public Employee(int empId, String empName, double empSalary,
String empDesign){
super();
this.empId = empId;
this.empName = empName;
this.empSalary = empSalary;
this.empDesign = empDesign;
}
@Override
public String toString() {
return "Employee [empId=" + empId + ", empName=" + empName
+ ", empSalary=" + empSalary + ", empDesign=" + empDesign
+ ", insuranceScheme=" + insuranceScheme + "]";
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public double getEmpSalary() {
return empSalary;
}
public void setEmpSalary(double empSalary){
this.empSalary = empSalary;
}
public String getEmpDesign() {
return empDesign;
}
public void setEmpDesign(String empDesign) {
this.empDesign = empDesign;
}
public String getInsuranceScheme() {
/*service=new EmployeeInsurance();
insuranceScheme = service.findScheme(empSalary, empDesign);
*/
return insuranceScheme;
}
public void setInsuranceScheme() {
EmployeeService service = new EmployeeInsurance();
try {
this.insuranceScheme = service.findScheme(empSalary, empDesign);
} catch (EmployeeException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
System.exit(0);
}
}
}
==========================================================================================
package assignment83.com.cg.eis.service;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.List;
import assignment83.com.cg.eis.bean.Employee;
import assignment83.exception.EmployeeException;
public class EmployeeInsurance implements EmployeeService {
private double salary;
private String designation;
@Override
public String findScheme(double salary,String designation) throws EmployeeException
{
String scheme="";
if(salary<3000){
throw new EmployeeException("Salary cannot be less than 3000");
//System.exit(0);
}
else if(salary >5000.0 && salary <20000.0 && designation.equals("System Associate"))
{
return scheme="Scheme C";
}
else if(salary >=20000.0 && salary <40000.0 && designation.equals("Programmer"))
{
return scheme="Scheme B";
}
else if(salary >=40000 && designation.equals("Manager"))
{
return scheme="Scheme A";
}
else if(salary<5000 && designation.equals("Clerk"))
{
return scheme="No Scheme";
}
return scheme;
}
@Override
public void addEmployeeToFile(List<Employee> list) {
try (FileOutputStream file=new FileOutputStream("D:\\Java Workspace\\Java Assignments\\src\\assignment83\\com\\cg\\eis\\data\\emp.ser");
OutputStream buffer=new BufferedOutputStream(file);
ObjectOutput output=new ObjectOutputStream(buffer);){
output.writeObject(list);
} catch ( IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try (InputStream file1=new FileInputStream("D:\\Java Workspace\\Java Assignments\\src\\assignment83\\com\\cg\\eis\\data\\emp.ser");
InputStream buffer=new BufferedInputStream(file1);
ObjectInput input=new ObjectInputStream(buffer);){
List<Employee> recover=(List<Employee>) input.readObject();
for(Employee val:recover)
{
System.out.println(val);
}
} catch ( IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
=======================================================================================================================================================
package assignment83.com.cg.eis.service;
import java.util.List;
import assignment83.exception.EmployeeException;
import assignment83.com.cg.eis.bean.Employee;
public interface EmployeeService {
public String findScheme(double salary,String designation) throws EmployeeException;
public void addEmployeeToFile(List<Employee> list);
}
=================================================================================================================
package assignment83.com.cg.eis.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import assignment83.com.cg.eis.bean.Employee;
public class TestEmployee {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*Scanner input=new Scanner(System.in);
System.out.println("Enter Employee Id ");
int empId=input.nextInt();
System.out.println("Enter Employee Name ");
String empName=input.next();
System.out.println("Enter Employee Salary ");
double empSal=input.nextDouble();
System.out.println("Enter Employee Designation ");
String empDesign=input.next();
Employee emp;
emp = new Employee(empId, empName, empSal, empDesign);
System.out.println("Employee Id ="+emp.getEmpId());
System.out.println("Employee Name ="+emp.getEmpName());
System.out.println("Employee Salary ="+emp.getEmpSalary());
System.out.println("Employee Designation ="+emp.getEmpDesign());
emp.setInsuranceScheme();
System.out.println("Employee Insurance Scheme ="+emp.getInsuranceScheme());
//emp.setEmpSalary(2000);*/
Employee emp=new Employee(100, "ross", 20000, "Programer");
emp.setInsuranceScheme();
Employee emp1=new Employee(101, "allen", 5000, "System Associate");
emp1.setInsuranceScheme();
Employee emp2=new Employee(102, "jack", 20000, "Programer");
emp2.setInsuranceScheme();
Employee emp3=new Employee(102, "mike", 50000, "Manager");
emp3.setInsuranceScheme();
EmployeeService service=new EmployeeInsurance();
List<Employee> list=new ArrayList<Employee>();
list.add(emp);
list.add(emp1);
list.add(emp2);
list.add(emp3);
service.addEmployeeToFile(list);
}
}
=====================================================================================
package com.capgemini.cg.eis.bean;
public class Employee {
public int id;
public String name,designation,insuranceScheme;
public double salary;
public Employee(int id, String name, String designation,String insuranceScheme,double salary) {
super();
this.id = id;
this.name = name;
this.designation = designation;
this.insuranceScheme = insuranceScheme;
this.salary = salary;
}
public Employee(){
}
}
================================================================================================================
package com.capgemini.cg.eis.exception;
import com.capgemini.cg.eis.bean.Employee;
import com.capgemini.cg.eis.pl.EmployeeServiceImpl;
public class CheckException {
public void checkSalary() throws EmployeeException{
EmployeeServiceImpl emp = new EmployeeServiceImpl();
Employee emp1 = emp.getEmpDetails();
if(emp1.salary<3000){
//EmployeeException e = new EmployeeException(emp1.salary);
//e.catchEmployeeException();
double salary = emp1.salary;
throw new EmployeeException("Salary less than 3000 :"+salary);
}
else{
String scheme = emp.insuranceScheme(emp1.designation, emp1.salary);
Employee person = new Employee(emp1.id,emp1.name,emp1.designation,scheme,emp1.salary);
emp.EmpDetails(person);
}
}
}
===============================================================================================================
package com.capgemini.cg.eis.exception;
public class EmployeeException extends Exception {
double salary;
public EmployeeException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public EmployeeException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
/*public EmployeeException(double salary){
this.salary = salary;
}
public void catchEmployeeException(){
try{
throw new EmployeeException("Salary less than 3000 :"+salary);
}
catch(EmployeeException e){
System.out.println(e.getMessage());
}
}*/
}
========================================================================================
package com.capgemini.cg.eis.exception;
import org.junit.Test;
import com.capgemini.cg.eis.bean.Employee;
import com.capgemini.cg.eis.pl.EmployeeServiceImpl;
public class JunitTestException {
//EmployeeServiceImpl emp = new EmployeeServiceImpl();
//Employee emp1 = emp.getEmpDetails();
CheckException check = new CheckException();
@Test(expected = EmployeeException.class)
public void CheckException() throws EmployeeException{
check.checkSalary();
}
}
===========================================================================
package com.capgemini.cg.eis.pl;
import com.capgemini.cg.eis.bean.Employee;
import com.capgemini.cg.eis.exception.CheckException;
import com.capgemini.cg.eis.exception.EmployeeException;
public class EmployeeMain {
public static void main(String[] args) {
CheckException check = new CheckException();
//check.checkSalary();
//System.out.println(emp1.name);
//emp.insuranceScheme();
}
}
==================================================================================
package com.capgemini.cg.eis.pl;
import java.util.Scanner;
import com.capgemini.cg.eis.bean.Employee;
import com.capgemini.cg.eis.service.EmployeeService;
public class EmployeeServiceImpl implements EmployeeService {
@Override
public Employee getEmpDetails() {
String designation;
String insuranceScheme = null;
Scanner in = new Scanner(System.in);
System.out.println("Enter employee id");
int id = in.nextInt();
System.out.println("Enter employee salary");
double salary = in.nextDouble();
System.out.println("Enter employee name");
String name = in.next();
if(salary<5000){
designation = "Clerk";
}
else if(salary>5000&&salary<20000){
designation = "System Associate";
}
else if(salary>=20000&&salary<40000){
designation = "Programmer";
}
else{
designation = "Manager";
}
Employee emp = new Employee(id,name,designation,insuranceScheme,salary);
return emp;
}
@Override
public String insuranceScheme(String designation,double salary) {
String scheme;
if(designation == "Clerk")
scheme = "No Scheme";
else if(designation == "System Associate")
scheme = "Scheme C";
else if(designation == "Programmer")
scheme = "Scheme B";
else
scheme = "Scheme A";
return scheme;
}
@Override
public void EmpDetails(Employee emp) {
System.out.println("Employee id"+emp.id);
System.out.println("Employee name"+emp.name);
System.out.println("Employee designation"+emp.designation);
System.out.println("Employee salary"+emp.salary);
System.out.println("Employee insurancescheme"+emp.insuranceScheme);
}
}
============================================================================================
package com.capgemini.cg.eis.service;
import com.capgemini.cg.eis.bean.Employee;
public interface EmployeeService {
public Employee getEmpDetails();
public String insuranceScheme(String designation,double Salary);
public void EmpDetails(Employee emp);
}
============================================================================================
package com.capgemini.com;
import static org.junit.Assert.*;
import junit.framework.Assert;
import org.junit.Test;
public class TestDate {
JunitDate date = new JunitDate(16,11,1993);
String date1 = "16/11/1993";
@Test
public void test() {
assertEquals(16,date.getIntDay());
}
@Test
public void test1(){
assertEquals(11,date.getIntMonth());
}
@Test
public void test2(){
assertEquals(1993,date.getIntYear());
}
/*@Test
public void test3() {
assertEquals(01,date.getIntDay());
}
@Test
public void test4(){
assertEquals(04,date.getIntMonth());
}
@Test
public void test5(){
assertEquals(2016,date.getIntYear());
}*/
@Test
public void test6(){
Assert.assertEquals(date1,date.toString());
}
}
==============================================================================
package com.capgemini.com;
import static org.junit.Assert.*;
import org.junit.Test;
public class PersonTestCase {
Person person = new Person("Soumik","Nath",'M');
DisplayDetails details = new DisplayDetails();
@Test
public void test() {
Person person1 = details.displayDetails("Sanit","Kundu", 'M');
assertEquals(person,person1);
//fail("Not yet implemented");
}
@Test
public void test1(){
Person person1 = details.displayDetails("Soumik","Nath",'M');
assertEquals(person,person1);
}
Person person1 = new Person("Vicky","Kumar",'M');
@Test
public void test2(){
assertEquals("Sanit",person1.getFirstName());
}
@Test
public void test3(){
person1.setFirstName("Sanit");
assertEquals("Sanit",person1.getFirstName());
}
@Test
public void test4(){
assertEquals("Kundu",person1.getLastName());
}
@Test
public void test5(){
person1.setLastName("Kundu");
assertEquals("Kundu",person1.getLastName());
}
@Test
public void test6(){
assertEquals('M',person1.getGender());
}
@Test
public void test7(){
person1.setGender('F');;
assertEquals("Sanit",person1.getGender());
}
}
=================================================================================
package com.capgemini.com;
public class Person {
private String firstName="",lastName="";
private char gender=' ';
public Person() {
}
public Person(String firstName,String lastName,char gender){
this.firstName = firstName;
this.lastName = lastName;
this.gender = gender;
}
/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* @param firstName the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* @return the lastName
*/
public String getLastName() {
return lastName;
}
/**
* @param lastName the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* @return the gender
*/
public char getGender() {
return gender;
}
/**
* @param gender the gender to set
*/
public void setGender(char gender) {
this.gender = gender;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result + gender;
result = prime * result
+ ((lastName == null) ? 0 : lastName.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (gender != other.gender)
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
return true;
}
}
==================================================================================
package com.capgemini.com;
public class JunitDate {
private int intDay,intMonth,intYear;
public JunitDate(int intDay, int intMonth, int intYear) {
super();
this.intDay = intDay;
this.intMonth = intMonth;
this.intYear = intYear;
}
/**
* @return the intDay
*/
public int getIntDay() {
return intDay;
}
/**
* @param intDay the intDay to set
*/
public void setIntDay(int intDay) {
this.intDay = intDay;
}
/**
* @return the intMonth
*/
public int getIntMonth() {
return intMonth;
}
/**
* @param intMonth the intMonth to set
*/
public void setIntMonth(int intMonth) {
this.intMonth = intMonth;
}
/**
* @return the intYear
*/
public int getIntYear() {
return intYear;
}
/**
* @param intYear the intYear to set
*/
public void setIntYear(int intYear) {
this.intYear = intYear;
}
@Override
public String toString() {
return""+intDay+"/"+intMonth+"/"+intYear;
}
}
==================================================================================
package com.capgemini.com;
import java.util.Scanner;
import java.math.*;
public class DisplayDetails {
Person person = new Person();
public Person displayDetails(String fname,String lname,char gender){
/*System.out.println("First Name : "+fname);
System.out.println("Last Name : "+lname);
System.out.println("Gender : "+gender);
System.out.println("PhoneNo. "+phoneno);*/
person.setFirstName(fname);
person.setLastName(lname);
person.setGender(gender);
return person;
}
}
=======================================================================================
package com.capgemini.com;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger;
public class CheckAge {
public void ageCheck(){
AtomicInteger count = new AtomicInteger(0);
Scanner in = new Scanner(System.in);
try {
Person smith = new Person("Smith",21);
int age = smith.getAge();
if(age<15)
throw new AgeException(smith.getName()+"'s age is less than 15");
Person kathy = new Person("Kathy",31);
age = kathy.getAge();
if(age<15)
throw new AgeException(kathy.getName()+"'s age is less than 15");
AccountAbstract smithsavingaccount = new SavingsAccount(count.incrementAndGet(),2000,smith);
AccountAbstract smithcurrentaccount = new CurrentAccount(count.incrementAndGet(),2000,smith);
System.out.println(smithsavingaccount);
System.out.println(smithcurrentaccount);
System.out.println("For AccountHolder Smith :");
/*if(choice=="deposit"&&type=="savings"){*/
System.out.println("Enter amount to deposit in savingsaccount");
double amount = in.nextDouble();
smithsavingaccount.deposit(amount);
System.out.println("Enter amount to withdraw in savings account ");
amount = in.nextDouble();
smithsavingaccount.withdraw(amount);
System.out.println("Enter amount to deposit in currentaccount");
amount = in.nextDouble();
smithcurrentaccount.deposit(amount);
System.out.println("Enter amount to withdraw in currentaccount");
amount = in.nextDouble();
smithcurrentaccount.withdraw(amount);
//smithaccount.deposit(2000);
//kathyaccount.withdraw(2000);
System.out.println("Balance in Smith's Current Account:");
smithcurrentaccount.getaccountBalance();
System.out.println("Balance in Smith's Savings Account:");
smithsavingaccount.getaccountBalance();
AccountAbstract kathysavingaccount = new SavingsAccount(count.incrementAndGet(),3000,kathy);
AccountAbstract kathycurrentaccount = new CurrentAccount(count.incrementAndGet(),3000,kathy);
System.out.println(kathysavingaccount);
System.out.println(kathycurrentaccount);
//System.out.println(smithaccount);
//System.out.println(kathyaccount);
/*System.out.println("Enter type of operation to perform for :Smith");
String choice = in.next();
System.out.println("Enter the account type:");
String type = in.next();*/
System.out.println("For AccountHolder Kathy :");
/*if(choice=="deposit"&&type=="savings"){*/
System.out.println("Enter amount to deposit in savingsaccount");
amount = in.nextDouble();
kathysavingaccount.deposit(amount);
System.out.println("Enter amount to withdraw in savings account ");
amount = in.nextDouble();
kathysavingaccount.withdraw(amount);
System.out.println("Enter amount to deposit in currentaccount");
amount = in.nextDouble();
kathycurrentaccount.deposit(amount);
System.out.println("Enter amount to withdraw in currentaccount");
amount = in.nextDouble();
kathycurrentaccount.withdraw(amount);
//smithaccount.deposit(2000);
//kathyaccount.withdraw(2000);
System.out.println("Balance in Kathy's Current Account:");
kathycurrentaccount.getaccountBalance();
System.out.println("Balance in Kathy's Savings Account:");
kathysavingaccount.getaccountBalance();
//System.out.println("Balance in Kathy's Account:");
//kathyaccount.getBalance();
} catch (AgeException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
}
}
}
=============================================================================================================================
#Soumik Nath M
#Fri Dec 16 10:04:05 IST 2016
#Fri Dec 16 10:04:05 IST 2016
Gender=M
FirstName=Soumik
LastName=Nath
===================================================
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
public class TestProperty {
public static void main(String[] args) {
String filePath="C:\\Users\\souminat\\Desktop\\Soumik_java\\Lab10\\src";
String fileName="PersonProps.txt";
//OutputStream os=null;
Properties p=new Properties();
Properties p1=new Properties();
System.out.println(filePath+"\\"+fileName);
try(OutputStream os = new FileOutputStream(filePath+"\\"+fileName);
FileInputStream in = new FileInputStream(filePath+"\\"+fileName);)
{
p.store(os,"Soumik Nath M");
//p.load(in);
//System.out.println(p.get("1#"));
//Storing the property by key
p.setProperty("FirstName","Soumik");
p.setProperty("LastName","Nath");
p.setProperty("Gender","M");
p.store(os,null);
p1.load(in);
//String name = in.getString("FirstName");
System.out.println(p1);
System.out.println(p1.getProperty("FirstName"));
System.out.println(p1.getProperty("LastName"));
System.out.println(p1.getProperty("Gender"));
//os.write('a');
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
========================================================================
package com.capgemini.cg.eis.bean;
public class Employee {
public int id;
public String name,designation,insuranceScheme;
public double salary;
public Employee(int id, String name, String designation,String insuranceScheme,double salary) {
super();
this.id = id;
this.name = name;
this.designation = designation;
this.insuranceScheme = insuranceScheme;
this.salary = salary;
}
public Employee(){
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Employee: id=" + id + ", name=" + name + ", designation="
+ designation + ", insuranceScheme=" + insuranceScheme
+ ", salary=" + salary;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (id != other.id)
return false;
return true;
}
}
==================================================================
package com.capgemini.cg.eis.pl;
import java.util.HashMap;
import java.util.Scanner;
import com.capgemini.cg.eis.bean.Employee;
import com.capgemini.cg.exceptions.DuplicateEmpException;
import com.capgemini.cg.exceptions.EmpMissingException;
public class EmployeeMain {
public static void main(String[] args)throws DuplicateEmpException, EmpMissingException{
EmployeeServiceImpl emp = new EmployeeServiceImpl();
String choice="";
Scanner in = new Scanner(System.in);
do{
System.out.println("1.Add Employee");
System.out.println("2.Delete Employee");
System.out.println("3.Show Employee Details");
System.out.println("4.Sort Employee Details");
System.out.println("Enter your choice");
int ch = in.nextInt();
switch(ch)
{
case 1:
System.out.println("Enter how many records to add");
int num = in.nextInt();
for(int index = 0;index<num;++index){
Employee emp1 = emp.getEmpDetails();
String scheme = emp.insuranceScheme(emp1.designation, emp1.salary);
Employee person = new Employee(emp1.id,emp1.name,emp1.designation,scheme,emp1.salary);
try {
emp.addEmp(person);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
}
}
break;
//System.out.println(emp1.name);
//emp.insuranceScheme();
//System.out.println("Hello");
case 2:
emp.EmpDetails();
System.out.println("Enter an employee id to delete the corresponding employee");
int id = in.nextInt();
try {
emp.delete(id);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 3:
emp.EmpDetails();
break;
case 4:
emp.sortEmp();
break;
default:
System.out.println("Invalid Choice");
}
System.out.println("Do you want to perform more operations: Yes/No");
choice = in.next();
}while(choice.equalsIgnoreCase("Yes"));
}
}
========================================================================================
package com.capgemini.cg.eis.pl;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.TreeSet;
import com.capgemini.cg.eis.bean.Employee;
import com.capgemini.cg.eis.service.EmployeeService;
import com.capgemini.cg.exceptions.DuplicateEmpException;
import com.capgemini.cg.exceptions.EmpMissingException;
public class EmployeeServiceImpl implements EmployeeService {
HashMap<String,Employee> empList = new HashMap<String,Employee>();
HashMap<String,Employee> empList1 = new HashMap<String,Employee>();
int recPosition = 0;
Map<String,Employee> map;
boolean flag = false;
@Override
public Employee getEmpDetails() {
String designation;
String insuranceScheme = null;
Scanner in = new Scanner(System.in);
System.out.println("Enter employee id");
int id = in.nextInt();
System.out.println("Enter employee salary");
double salary = in.nextDouble();
System.out.println("Enter employee name");
String name = in.next();
if(salary<5000){
designation = "Clerk";
}
else if(salary>5000&&salary<20000){
designation = "System Associate";
}
else if(salary>=20000&&salary<40000){
designation = "Programmer";
}
else{
designation = "Manager";
}
Employee emp = new Employee(id,name,designation,insuranceScheme,salary);
return emp;
}
@Override
public String insuranceScheme(String designation,double salary) {
String scheme;
if(designation == "Clerk")
scheme = "No Scheme";
else if(designation == "System Associate")
scheme = "Scheme C";
else if(designation == "Programmer")
scheme = "Scheme B";
else
scheme = "Scheme A";
return scheme;
}
@Override
public void EmpDetails(){
//System.out.println("hello");
//Iterator<String> it = empList.keySet().iterator();
for(String empNo:empList.keySet()){
System.out.println("Position "+empNo+" "+"Record "+empList.get(empNo));
//System.out.println("hello");
}
//System.out.println(empList);
}
@Override
public void addEmp(Employee emp) throws DuplicateEmpException{
//Employee emp = getEmpDetails();
//String scheme = insuranceScheme(emp.designation,emp.salary);
//Employee emp1 = new Employee(emp.id,emp.name,emp.designation,scheme,emp.salary);
if(recPosition == 0){
empList.put("record"+emp.id,emp);
System.out.println("Employee added");
System.out.println("Position"+recPosition+"Record"+empList.get("record"+emp.id));
++recPosition;
}
else
{
if(checkEmp(emp.id) !=null){
emp = checkEmp(emp.id);
throw new DuplicateEmpException("Record already exists: "+emp);
}
else{
empList.put("record"+emp.id,emp);
System.out.println("Employee added");
System.out.println("Position"+recPosition+"Record"+empList.get("record"+emp.id));
++recPosition;
}
}
//return empList;
}
public boolean delete(int id)throws EmpMissingException{
for(String empNo:empList.keySet()){
if((empList.get(empNo)).id == id){
Employee emp1 = empList.get(empNo);
empList.remove(empNo);
System.out.println("Record: "+emp1+"deleted");
flag = true;
return flag;
}
}
if(flag == false){
throw new EmpMissingException("Employee Id Not found");
}
return flag;
//--recPosition;
}
@Override
public Employee checkEmp(int id) {
for(String empNo:empList.keySet()){
if(id == empList.get(empNo).id){
return empList.get(empNo);
}
}
return null;
}
@Override
public void sortEmp() {
for(String empNo:empList.keySet()){
Employee emp = empList.get(empNo);
empList1.put("Salary" +emp.salary, emp);
}
map = new TreeMap<String,Employee>(empList1);
//map.p
/*for(String empNo:empList.keySet()){
empList.remove(empNo);
}*/
//empList.putAll(map);
System.out.println("Records after sorting");
//double sal = 200000;
System.out.println(map);
//System.out.println("hello");
/*for(int index = 0;index<recPosition;++index){
set.add(empList.get("record"+index));
empList.remove("record"+index);
}
for(int index = 0;index<recPosition;++index){
empList.put("record"+recPosition, set.first());
set.remove(empList.get("record"+recPosition));
}*/
}
}
================================================================================
package com.capgemini.cg.eis.service;
import java.util.HashMap;
import com.capgemini.cg.eis.bean.Employee;
import com.capgemini.cg.exceptions.DuplicateEmpException;
import com.capgemini.cg.exceptions.EmpMissingException;
public interface EmployeeService {
public Employee getEmpDetails();
public String insuranceScheme(String designation,double Salary);
public void EmpDetails();
public void addEmp(Employee emp)throws DuplicateEmpException;
public boolean delete(int id)throws EmpMissingException;
public Employee checkEmp(int id);
public void sortEmp();
//public void deleteEmp(int index);
}
======================================================================================
package com.capgemini.cg.exceptions;
public class DuplicateEmpException extends Exception {
public DuplicateEmpException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public DuplicateEmpException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
}
========================================================================================
package com.capgemini.cg.exceptions;
public class EmpMissingException extends Exception {
public EmpMissingException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public EmpMissingException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
}
=========================================================================================
package com.capgemini.core.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import org.apache.log4j.Logger;
import com.capgemini.core.dto.Mobiles;
import com.capgemini.core.dto.PurchaseDetails;
import com.capgemini.core.exception.MobileIdNotFoundException;
import com.capgemini.core.util.DBUtil;
public class CustDAOImpl implements ICustDAO {
Scanner sc=new Scanner(System.in);
static Logger myLogger = Logger.getLogger(CustDAOImpl.class.getName());
@Override
public boolean addPurchaseDetails(PurchaseDetails purchase) throws MobileIdNotFoundException {
Connection con=null;
PreparedStatement pst=null;
try {
con=DBUtil.getConnection();
pst=con.prepareStatement("insert into purchase_details values(purchase_seq.nextval,?,?,?,?,?)");
//pst.setInt(1, purchase.getPurchaseId());
pst.setString(1, purchase.getCname());
pst.setString(2, purchase.getMailid());
pst.setString(3, purchase.getPhoneno());
pst.setDate(4, purchase.getDate());
pst.setInt(5, purchase.getMobileId());
pst.execute();
//con.prepareStatement("commit");
} catch (SQLException e) {
myLogger.error(e.getMessage());
e.printStackTrace();
}catch(Exception e){
myLogger.warn(e.getMessage());
}
finally{
try {
if(con!=null){
con.close();
}
} catch (SQLException e) {
myLogger.fatal("Connection could not be established");
}
}
return false;
}
@Override
public Mobiles deleteMobileDetails(int mobileId) throws MobileIdNotFoundException {
Mobiles mobile=null;
Connection con=null;
PreparedStatement pst=null;
try {
con=DBUtil.getConnection();
pst=con.prepareStatement("delete from mobiles where mobileId=?");
pst.setInt(1,mobileId);
int count=pst.executeUpdate();
if(count==0){
throw new MobileIdNotFoundException("Mobile Id is not found");
}
System.out.println("Mobile details deleted");
} catch (SQLException e) {
myLogger.warn(e.getMessage());
/*e.printStackTrace();
System.out.println("Mobile id doesn't exist");*/
}catch(Exception e){
myLogger.warn(e.getMessage());
}
finally{
if(con!=null){
try {
con.close();
} catch (SQLException e) {
myLogger.fatal("Connection could not be established");
}
}
}
return mobile;
}
@Override
public Mobiles updateMobileDetails(int mobileId) throws MobileIdNotFoundException {
Mobiles mobiles=null;
Connection con=null;
PreparedStatement pst=null;
try {
con=DBUtil.getConnection();
pst=con.prepareStatement("select * from mobiles where mobileId=?");
pst.setInt(1, mobileId);
ResultSet rs=pst.executeQuery();
if(!rs.next()){
throw new MobileIdNotFoundException("Mobile id doesn't exist");
}
System.out.println("Enter new mobile name");
String name=sc.next();
System.out.println("Enter new mobile price");
int price=sc.nextInt();
System.out.println("Enter new mobile quantity");
int quantity=sc.nextInt();
pst=con.prepareStatement("update mobiles set name=?,price=?,quantity=? where mobileId=?");
pst.setString(1,name);
pst.setInt(2, price);
pst.setInt(3, quantity);
pst.setInt(4,mobileId);
int count=pst.executeUpdate();
if(count==0){
throw new MobileIdNotFoundException("Mobile id doesn't exist");
}
System.out.println("Succesfully updated");
} catch (SQLException e) {
myLogger.error(e.getMessage());
}
catch(Exception e){
myLogger.warn(e.getMessage());
}
return mobiles;
}
@Override
public List<Mobiles> getMobileDetails() throws MobileIdNotFoundException {
List<Mobiles> mobiles=new ArrayList<Mobiles>();
ResultSet res=null;
Connection con=null;
PreparedStatement pst=null;
try {
con=DBUtil.getConnection();
pst=con.prepareStatement("select * from mobiles");
res=pst.executeQuery();
while(res.next()){
Mobiles mob=new Mobiles();
mob.setMobileId(res.getInt("mobileId"));
mob.setName(res.getString("name"));
mob.setPrice(res.getInt("price"));
mob.setQuantity(res.getInt("quantity"));
mobiles.add(mob);
}
} catch (SQLException e) {
myLogger.error(e.getMessage());
e.printStackTrace();
}
catch(Exception e){
myLogger.warn(e.getMessage());
}
finally{
if(con!=null){
try {
con.close();
} catch (SQLException e) {
myLogger.fatal("Connection could not be established");
}
}
}
if(mobiles.isEmpty()){
throw new MobileIdNotFoundException("No mobile exists in database");
}
return mobiles;
}
@Override
public List<Mobiles> searchMobile(int lrange,int hrange) throws MobileIdNotFoundException {
List<Mobiles> mobiles=new ArrayList<Mobiles>();
Connection con=null;
PreparedStatement pst=null;
try {
con=DBUtil.getConnection();
pst=con.prepareStatement("select * from mobiles where price>=? and price <=?");
pst.setInt(1, lrange);
pst.setInt(2, hrange);
ResultSet rs=pst.executeQuery();
while(rs.next()){
Mobiles mob=new Mobiles();
mob.setMobileId(rs.getInt("mobileId"));
mob.setName(rs.getString("name"));
mob.setPrice(rs.getInt("price"));
mob.setQuantity(rs.getInt("quantity"));
System.out.println(mob.getMobileId());
System.out.println(mob.getName());
System.out.println(mob.getPrice());
System.out.println(mob.getQuantity());
}
rs=pst.executeQuery();
if(!rs.next()){
throw new MobileIdNotFoundException("Mobile in this price range doesn't exist");
}
} catch (Exception e) {
myLogger.error(e.getMessage());
System.out.println("Mobile in this price range doesn't exist");
}
finally{
if(con!=null){
try {
con.close();
} catch (SQLException e) {
myLogger.fatal("Connection could not be established");
}
}
}
return mobiles;
}
}
=========================================================================================================
package com.capgemini.core.dao;
import java.util.List;
import com.capgemini.core.dto.Mobiles;
import com.capgemini.core.dto.PurchaseDetails;
import com.capgemini.core.exception.MobileIdNotFoundException;
public interface ICustDAO {
public boolean addPurchaseDetails(PurchaseDetails purchase) throws MobileIdNotFoundException;
public Mobiles deleteMobileDetails(int mobileId) throws MobileIdNotFoundException;
public Mobiles updateMobileDetails(int mobileId) throws MobileIdNotFoundException;
public List<Mobiles> getMobileDetails() throws MobileIdNotFoundException;
public List<Mobiles> searchMobile(int lrange,int hrange) throws MobileIdNotFoundException;
}
=========================================================================================================
package com.capgemini.core.dto;
import java.io.Serializable;
public class Mobiles implements Serializable
{
private static final long serialVersionUID = 1L;
private int mobileId;
private String name;
private int price;
private int quantity;
public Mobiles(int mobileId, String name, int price, int quantity) {
super();
this.mobileId = mobileId;
this.name = name;
this.price = price;
this.quantity = quantity;
}
public Mobiles() {
super();
}
public int getMobileId() {
return mobileId;
}
public void setMobileId(int mobileId) {
this.mobileId = mobileId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + mobileId;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Mobiles other = (Mobiles) obj;
if (mobileId != other.mobileId)
return false;
return true;
}
@Override
public String toString() {
return "Mobiles [mobileId=" + mobileId + ", name=" + name + ", price="
+ price + ", quantity=" + quantity + "]";
}
}
===================================================================================================
package com.capgemini.core.dto;
import java.io.Serializable;
import java.sql.Date;
public class PurchaseDetails implements Serializable
{
private static final long serialVersionUID = 1L;
private int purchaseId;
private String cname;
private String mailid;
private String phoneno;
private Date date;
private int mobileId;
public PurchaseDetails(int purchaseId, String cname, String mailid,
String phoneno, Date date, int mobileId)
{
super();
this.purchaseId = purchaseId;
this.cname = cname;
this.mailid = mailid;
this.phoneno = phoneno;
this.date = date;
this.mobileId = mobileId;
}
public PurchaseDetails() {
super();
}
public int getPurchaseId() {
return purchaseId;
}
public void setPurchaseId(int purchaseId) {
this.purchaseId = purchaseId;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getMailid() {
return mailid;
}
public void setMailid(String mailid) {
this.mailid = mailid;
}
public String getPhoneno() {
return phoneno;
}
public void setPhoneno(String phoneno) {
this.phoneno = phoneno;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public int getMobileId() {
return mobileId;
}
public void setMobileId(int mobileId) {
this.mobileId = mobileId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + purchaseId;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PurchaseDetails other = (PurchaseDetails) obj;
if (purchaseId != other.purchaseId)
return false;
return true;
}
@Override
public String toString() {
return "PurchaseDetails [purchaseId=" + purchaseId + ", cname=" + cname
+ ", mailid=" + mailid + ", phoneno=" + phoneno + ", date="
+ date + ", mobileId=" + mobileId + "]";
}
}
===========================================================================================================
package com.capgemini.core.exception;
public class MobileIdNotFoundException extends Exception {
public MobileIdNotFoundException() {
super();
// TODO Auto-generated constructor stub
}
public MobileIdNotFoundException(String arg0, Throwable arg1, boolean arg2,
boolean arg3) {
super(arg0, arg1, arg2, arg3);
// TODO Auto-generated constructor stub
}
public MobileIdNotFoundException(String arg0, Throwable arg1) {
super(arg0, arg1);
// TODO Auto-generated constructor stub
}
public MobileIdNotFoundException(String arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
public MobileIdNotFoundException(Throwable arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
}
=============================================================
package com.capgemini.core.service;
import java.util.List;
import com.capgemini.core.dao.CustDAOImpl;
import com.capgemini.core.dao.ICustDAO;
import com.capgemini.core.dto.Mobiles;
import com.capgemini.core.dto.PurchaseDetails;
import com.capgemini.core.exception.MobileIdNotFoundException;
public class CustServicesImpl implements ICustServices {
ICustDAO custdao=new CustDAOImpl();
@Override
public boolean addPurchaseDetails(PurchaseDetails purchase) throws MobileIdNotFoundException {
return custdao.addPurchaseDetails(purchase);
}
@Override
public Mobiles deleteMobileDetails(int mobileId) throws MobileIdNotFoundException {
return custdao.deleteMobileDetails(mobileId);
}
@Override
public Mobiles updateMobileDetails(int mobileId) throws MobileIdNotFoundException {
return custdao.updateMobileDetails(mobileId);
}
@Override
public List<Mobiles> getMobileDetails() throws MobileIdNotFoundException {
return custdao.getMobileDetails();
}
@Override
public List<Mobiles> searchMobile(int lrange,int hrange) throws MobileIdNotFoundException {
return custdao.searchMobile(lrange,hrange);
}
}
=========================================================================================================
package com.capgemini.core.service;
import java.util.List;
import com.capgemini.core.dto.Mobiles;
import com.capgemini.core.dto.PurchaseDetails;
import com.capgemini.core.exception.MobileIdNotFoundException;
public interface ICustServices {
public boolean addPurchaseDetails(PurchaseDetails purchase) throws MobileIdNotFoundException;
public Mobiles deleteMobileDetails(int mobileId) throws MobileIdNotFoundException;
public Mobiles updateMobileDetails(int mobileId) throws MobileIdNotFoundException;
public List<Mobiles> getMobileDetails() throws MobileIdNotFoundException;
public List<Mobiles> searchMobile(int lrange,int hrange) throws MobileIdNotFoundException;
}
===========================================================================================================
package com.capgemini.core.test;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.PropertyConfigurator;
import org.junit.BeforeClass;
import org.junit.Test;
import com.capgemini.core.dao.CustDAOImpl;
import com.capgemini.core.dao.ICustDAO;
import com.capgemini.core.dto.Mobiles;
import com.capgemini.core.dto.PurchaseDetails;
import com.capgemini.core.exception.MobileIdNotFoundException;
public class Junittest2 {
public static ICustDAO custdao;
@BeforeClass
public static void initServices(){
custdao=new CustDAOImpl();
PropertyConfigurator.configure("D:\\SandeepJAVA\\MobilePurchaseSystem\\resources\\log4j.properties");
}
@Test
public void testAdd() throws MobileIdNotFoundException{
java.util.Date date=new java.util.Date();
java.sql.Date purchaseDate=new java.sql.Date(date.getTime());
PurchaseDetails purchase=new PurchaseDetails(101,"Suvo","aa@gmail.com","9674345725",purchaseDate,1001);
assertEquals(false,custdao.addPurchaseDetails(purchase));
}
@Test
public void testSearch(){
try {
List<Mobiles> mobiles=new ArrayList<Mobiles>();
assertEquals(mobiles,custdao.searchMobile(8000,40000));
} catch (MobileIdNotFoundException e) {
e.printStackTrace();
}
}
}
============================================================================================
package com.capgemini.core.ui;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import org.apache.log4j.PropertyConfigurator;
import com.capgemini.core.supriyo.mps.dto.Mobiles;
import com.capgemini.core.supriyo.mps.dto.PurchaseDetails;
import com.capgemini.core.supriyo.mps.exception.MobileIdNotFoundException;
import com.capgemini.core.supriyo.mps.service.CustServicesImpl;
import com.capgemini.core.supriyo.mps.service.ICustServices;
public class MPS_UI {
ICustServices custservices=new CustServicesImpl();
String ch=" ";
public void startApp(){
do{
Scanner console=new Scanner(System.in);
int choice=0;
System.out.println("MPS Operation");
System.out.println("1) Add Customer & Purchase Details");
System.out.println("2) Remove Mobile Details");
System.out.println("3) Update Mobile Details");
System.out.println("4) View Mobile Details");
System.out.println("5) Search Mobiles");
System.out.println("6) Exit");
System.out.println("Enter your choice");
choice=console.nextInt();
switch(choice){
case 1:
{
ValidateInputs inputs=new ValidateInputs();
System.out.println("Provide Customer & Purchase Details");
System.out.println("Enter Customer Name");
String name=console.next();
while(!inputs.validateCustomerName(name)){
System.out.println("invalid");
System.out.println("Enter Customer Name again");
name=console.next();
}
System.out.println("Enter mail id");
String mail=console.next();
while(!inputs.validateEmailId(mail)){
System.out.println("invalid");
System.out.println("Enter mail id again");
mail=console.next();
}
System.out.println("Enter Phone no");
String phno=console.next();
while(!inputs.validateMobileNumber(phno)){
System.out.println("invalid");
System.out.println("Phone number number again");
phno=console.next();
}
java.util.Date date=new java.util.Date();
java.sql.Date purchaseDate=new java.sql.Date(date.getTime());
System.out.println("Enter mobile id");
int mobid=console.nextInt();
Integer x=mobid;
String str=x.toString();
while(!inputs.validateMobileId(str)){
System.out.println("invalid");
System.out.println("Phone Mobile Id again");
mobid=console.nextInt();
x=mobid;
str=x.toString();
}
PurchaseDetails purchase=new PurchaseDetails(0,name,mail,phno,purchaseDate,mobid);
try {
custservices.addPurchaseDetails(purchase);
} catch (MobileIdNotFoundException e) {
System.out.println("Something went wrong while adding details");
System.out.println("Error :"+e.getMessage());
e.printStackTrace();
}
System.out.println("Succesfully Inserted");
break;
}
case 2:
{
System.out.println("\n\n");
System.out.println("Enter mobile Id");
int id1=console.nextInt();
try {
Mobiles mobiles=custservices.deleteMobileDetails(id1);
} catch (MobileIdNotFoundException e) {
System.out.println("Mobile id doesn't exist");
//System.out.println(e.getMessage());
}
break;
}
case 3:
{
System.out.println("enter mobile id");
int mobid=console.nextInt();
try {
custservices.updateMobileDetails(mobid);
} catch (MobileIdNotFoundException e) {
System.out.println("Mobile id doesn't exist");
e.getMessage();
}
break;
}
case 4:
{
try {
System.out.println("\n\n");
//System.out.println("hola");
List<Mobiles> mobiles=custservices.getMobileDetails();
Iterator<Mobiles> it = mobiles.iterator();
while(it.hasNext()){
Mobiles mobile=it.next();
System.out.println("Mobile id:"+mobile.getMobileId());
System.out.println("Mobile Name"+mobile.getName());
System.out.println("Mobile price:"+mobile.getPrice());
System.out.println("Mobile quantity:"+mobile.getQuantity());
}
} catch (MobileIdNotFoundException e) {
e.getMessage();
}
break;
}
case 5:
{
System.out.println("Enter lower price range");
int lrange=console.nextInt();
System.out.println("Enter higher price range");
int hrange=console.nextInt();
try {
custservices.searchMobile(lrange,hrange);
} catch (MobileIdNotFoundException e) {
e.getMessage();
}
break;
}
case 6:
{
System.out.println("Good Bye");
System.exit(0);
break;
}
}
System.out.println("Do you want to continue? YES/NO");
ch=console.next();
}while(ch.equalsIgnoreCase("yes"));
}
public static void main(String[] args) {
PropertyConfigurator.configure("D:\\SupriyoJAVA\\MobilePurchaseSystem\\resources\\log4j.properties");
MPS_UI app=new MPS_UI();
app.startApp();
}
}
=========================================================================================================================
package com.capgemini.core.ui;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ValidateInputs {
Scanner console=new Scanner(System.in);
public boolean validateMobileNumber(String strMobileNo){
Pattern pattern=Pattern.compile("^[0-9]{10}");
Matcher matcher=pattern.matcher(strMobileNo);
return matcher.matches();
}
public boolean validateCustomerName(String strName){
Pattern pattern=Pattern.compile("^[A-Z][a-z]*{0,19}");
Matcher matcher=pattern.matcher(strName);
return matcher.matches();
}
public boolean validateEmailId(String strEmail){
Pattern pattern=Pattern.compile("^[A-Za-z0-9._]*@[a-z]*.(com|in|org)");
Matcher matcher=pattern.matcher(strEmail);
return matcher.matches();
}
public boolean validateMobileId(String mobileId){
Pattern pattern=Pattern.compile("^(1001|1002|1003)");
Matcher matcher=pattern.matcher(mobileId);
return matcher.matches();
}
@SuppressWarnings("deprecation")
public boolean validateDate(String date){
DateTimeFormatter formatter=DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate datenow=LocalDate.now();
LocalDate date1=LocalDate.parse(date, formatter);
/*String str=date1.toString();
System.out.println(str);*/
if(datenow==date1){
return true;
}else{
return false;
}
}
}
========================================================================================
package com.capgemini.core.util;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import oracle.jdbc.pool.OracleDataSource;
//singleton class
public class DBUtil { //factory class
private static OracleDataSource ods;
static{
try {
ods=new OracleDataSource();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException{
String filePath="D:\\SupriyoJAVA\\MobilePurchaseSystem\\resources";
String fileName="Database.properties";
FileReader reader=null;
Properties properties=null;
Connection connection;
try {
reader = new FileReader(filePath+"\\"+fileName);
properties=new Properties();
properties.load(reader);
connection = null;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
ods.setUser(properties.getProperty("userName"));
ods.setPassword(properties.getProperty("password"));
ods.setDriverType("thin");
ods.setNetworkProtocol("tcp");
ods.setURL(properties.getProperty("url"));
connection=ods.getConnection();
return connection;
}
public static void main(String[] args) throws SQLException, IOException {
Connection connection=DBUtil.getConnection();
if(connection!=null){
System.out.println(connection.getMetaData().getDatabaseProductName());
}
else{
System.out.println("connection not successful");
}
}
}
Assignment 1
2.1
====
public class Person
{
public static void main(String[] args)
{
System.out.println("Person Details");
System.out.println("-------------------------");
System.out.println("First Name : Divya");
System.out.println("Last Name : Bharathi");
System.out.println("Gender : F");
System.out.println("Age : 20");
System.out.println("Weight : 85.55");
System.out.println("--------------------------");
}
}
==================================================================
2.2
====
import java.util.Scanner;
public class Person
{
public static void main(String[] args)
{
int number=0;
System.out.print("Enter a Number:");
Scanner object=new Scanner(System.in);
number = object.nextInt();
if(number>0)
{
System.out.println("Input Number is Positive");
}
else
{
System.out.println("Input Number is Negative");
}
}
}
======================================================================
2.3
====
Person Class
==============
package com.capgemini.corp.classes;
import java.util.Scanner;
public class Person
{
String FirstName;
String LastName;
char gender;
int age;
double weight;
//Getters Setters
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String firstName) {
FirstName = firstName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
//Constructor
public Person() {
super();
}
public Person(String firstName, String lastName, char gender, int age,
double weight) {
super();
FirstName = firstName;
LastName = lastName;
this.gender = gender;
this.age = age;
this.weight = weight;
}
public void printDetails()
{
System.out.println("Person Details");
System.out.println("-------------------------");
System.out.println("First Name : "+FirstName);
System.out.println("Last Name : "+LastName);
System.out.println("Gender : "+gender);
System.out.println("Age : "+age);
System.out.println("Weight : "+weight);
System.out.println("--------------------------");
}
}
==========================================================
import java.util.Scanner;
public class TestPerson
{
public static void main(String[] args)
{
Person object =new Person();
Scanner object1 = new Scanner(System.in);
System.out.println("Enter First Name:");
object.setFirstName((object1.next()));
System.out.println("Enter Last Name:");
object.setLastName((object1.next()));
System.out.println("Enter Gender:");
object.setGender(object1.next().charAt(0));
System.out.println("Enter Age:");
object.setAge(object1.nextInt());
System.out.println("Enter Weight:");
object.setWeight(object1.nextDouble());
System.out.println("\n\n");
object.printDetails();
}
}
=============================================================
2.4
======
Person Class
=============
import java.util.Scanner;
public class Person
{
String FirstName;
String LastName;
char gender;
int age;
double weight;
long phonenumber;
//Getters Setters
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String firstName) {
FirstName = firstName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public long getPhonenumber() {
return phonenumber;
}
public void setPhonenumber(long phonenumber) {
this.phonenumber = phonenumber;
}
//Constructor
public Person() {
super();
}
public Person(String firstName, String lastName, char gender, int age,
double weight, long phonenumber) {
super();
FirstName = firstName;
LastName = lastName;
this.gender = gender;
this.age = age;
this.weight = weight;
this.phonenumber = phonenumber;
}
public void printDetails()
{
System.out.println("Person Details");
System.out.println("-------------------------");
System.out.println("First Name : "+FirstName);
System.out.println("Last Name : "+LastName);
System.out.println("Gender : "+gender);
System.out.println("Age : "+age);
System.out.println("Weight : "+weight);
System.out.println("Phone Number:"+phonenumber);
System.out.println("--------------------------");
}
}
================================================================
import java.util.Scanner;
public class TestPerson
{
public static void main(String[] args)
{
Person object =new Person();
Scanner object1 = new Scanner(System.in);
System.out.println("Enter First Name:");
object.setFirstName((object1.next()));
System.out.println("Enter Last Name:");
object.setLastName((object1.next()));
System.out.println("Enter Gender:");
object.setGender(object1.next().charAt(0));
System.out.println("Enter Age:");
object.setAge(object1.nextInt());
System.out.println("Enter Weight:");
object.setWeight(object1.nextDouble());
System.out.println("Enter Phone Number:");
object.setPhonenumber(object1.nextLong());
System.out.println("\n\n");
object.printDetails();
}
}
================================================================
2.5
====
====
enum Gender {
M, F;
}
public class PersonEnum
{
private String firstName;
private String lastName;
private Gender gender ;
String phoneNo;
public PersonEnum(String firstName, String lastName, Gender gender,
String phoneNo) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.gender = gender;
this.phoneNo = phoneNo;
}
public PersonEnum()
{
super();
this.firstName = null;
this.lastName = null;
this.phoneNo = null;
}
public void displayDetails()
{
System.out.println("Person Details");
System.out.println("---------------------------------");
System.out.println("First Name: " + this.firstName);
System.out.println("Last Name: " + this.lastName);
System.out.println("Gender: " + this.gender);
System.out.println("Phone no: " + this.phoneNo);
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public Gender getGender()
{
return gender;
}
public void setGender(Gender gender)
{
this.gender = gender;
}
public String getPhoneNo()
{
return phoneNo;
}
public void setPhoneNo(String phoneNo)
{
this.phoneNo = phoneNo;
}
}
=============================
public class PersonEnumMain
{
public static void main(String[] args)
{
PersonEnum p1 = new PersonEnum("clark", "kent", Gender.M , "785459577");
p1.displayDetails();
}
}
==========================================================================================
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment