I'm trying to calculate a simple banking function.I passed two withdraw value 150 and 47.62 through one method from execution class to another.But it takes 47.62 twice and giving me wrong result here is the execution class.
public class Account {
public double balance ;
public double deposite;
public double withdraw;
public Account(double balance) {
this.balance = balance;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public double getDeposite() {
balance = balance + deposite;
return deposite;
}
public void setDeposite(double deposite) {
this.deposite = deposite;
}
public double getWithdraw() {
return withdraw;
}
public void setWithdraw(double withdraw) {
this.withdraw = withdraw;
if(withdraw <= balance){
balance = balance - withdraw;
}
}
public boolean withdraw(double wamt)
{
boolean result = false;
if(withdraw <= wamt)
{
balance= balance - withdraw;
return true;
}
return result;
}
}
My customer class
public class Customer {
private String firstName;
private String lastName;
Account account;
public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
//this.account = account;
}
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 Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account; }
}
Main class:
public class BankProjectDemo {
public static void main(String[] args) {
double balance = 500;
Customer cust = new Customer("asasd0","asdasda");
Account accnt = new Account(balance);
System.out.println("Creating customer: " +cust.getFirstName());
accnt.setWithdraw(150);
accnt.setDeposite(22.50);
System.out.println("Withdraw1 "+accnt.getWithdraw());
System.out.println("Depsoite "+accnt.getDeposite());
Account accnt1 = new Account(balance);
accnt1.setWithdraw(47.62);
System.out.println("Withdraw2 "+accnt1.getWithdraw()+" " + accnt1.withdraw(balance));
System.out.println("Balance " + accnt.getBalance());
}
}
public boolean withdraw(double wamt)
{
boolean result = false;
if(withdraw <= wamt)
{
balance= balance - withdraw;
return true;
}
return result;
}
You reduce your Balance both withdraw() and setWithdraw() So you set it once and then reduce again on your system println thats why at the end you get twice the reduction
public double getDeposite() {
balance = balance + deposite;
return deposite;
}
This method looks wrong, every time you return a variable you're incrementing another - this means the more you call this method, the bigger the balance gets. Is this by intent?
Also - you should look into some basic unit testing as well as debugging so it's clearer to see exactly what is happening with different variables.
Maybe the problem is here
System.out.println("Balance " + accnt.getBalance());
It should be
System.out.println("Balance " + accnt1.getBalance());
Related
My programming assignment tasked me with writing an increase/decreasePay abstract method that must be put in my abstract employee class. I can't seem to get the the method correct in HourlyWorker so that it will take increase or decrease the pay by a "percentage". My math is sound (monthly pay - or + (monthly pay * the percentage), but my output in my test class is coming out the same after increasing/decreasing pay. Any help?
Employee class:
abstract public class Employee
{
private String lastName;
private String firstName;
private String ID;
public abstract void increasePay(double percentage);
public abstract void decreasePay(double percentage);
public abstract double getMonthlyPay();
public Employee(String last, String first, String ID)
{
lastName = last;
firstName = first;
this.ID = ID;
}
public void setLast(String last)
{
lastName = last;
}
public void setFirst(String first)
{
firstName = first;
}
public void setIdNumber(String ID)
{
this.ID = ID;
}
public String getLastName()
{
return lastName;
}
public String getFirstName()
{
return firstName;
}
public String getName()
{
return firstName + lastName;
}
public String getIdNumber()
{
return ID;
}
}
HourlyWorkerClass
public class HourlyWorker extends Employee
{
private int hours;
private double hourlyRate;
private double monthlyPay;
public HourlyWorker(String last, String first, String ID, double rate)
{
super(last, first, ID);
hourlyRate = rate;
}
public void setHours(int hours)
{
this.hours = hours;
}
public int getHours()
{
return hours;
}
public void setHourlyRate(double rate)
{
if ( hours > 160 )
this.hourlyRate = hourlyRate * 1.5;
else
this.hourlyRate = rate;
}
public double getHourlyRate()
{
return hourlyRate;
}
public void setMonthlyPay(double monthlyPay)
{
monthlyPay = hourlyRate * hours;
}
public double getMonthlyPay()
{
return hourlyRate * hours;
}
public void increasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public void decreasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public String toString()
{
String result = "Name: " + getFirstName() + " " + getLastName() + "\nID: "
+ getIdNumber() + " \nHourly Rate: " + hourlyRate;
return result;
}
}
Testing class (currently testing increase
public class TestEmployee2
{
public static void main(String[] args)
{
Employee [] staff = new Employee[3];
Supervisor sup = new Supervisor("Boss", "Jim", "JB7865", 54000);
HourlyWorker hw1 = new HourlyWorker("Bee", "Busy", "BB1265", 11.95);
hw1.setHours(200);
staff[0] = sup;
staff[1] = hw1;
System.out.println(staff[0].getMonthlyPay());
staff[0].increasePay(5);
System.out.println(staff[0].getMonthlyPay());
System.out.println(staff[1].getMonthlyPay());
staff[1].increasePay(10);
System.out.println(staff[1].getMonthlyPay());
}
}
Supervisor class:
public class Supervisor extends Employee
{
private double annualSalary;
private double monthlyPay;
public Supervisor(String last, String first, String ID, double salary)
{
super(last, first, ID);
annualSalary = salary;
}
public void setAnnualSalary(double salary)
{
annualSalary = salary;
}
public double getAnnualSalary()
{
return annualSalary;
}
public double getMonthlyPay()
{
return ((annualSalary + (annualSalary * .02)) / 12);
}
public void increasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public void decreasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public String toString()
{
String result = "Name: " + getFirstName() + " " + getLastName() + "\nID: "
+ getIdNumber() + "\nAnnual Salary: " + annualSalary;
return result;
}
}
Output is:
4590.0 4590.0 2390.0 2390.0
Doesn't appear to be modifying getMonthlyPay()
Should be:
4590.00 4819.50 2390.00 2629.00
Generally, when implementing equals(), you compare “key” fields whose values don’t change for the entity, and don’t compare “state” fields whose values change from time to time.
You are comparing sharePrice, when I believe you should be comparing symbol.
When you do list.indexOf(temp), what that does, right now, is look for a Stock that is equals to the argument passed to it -- so it looks for a Stock with price zero, not caring about the symbol at all. That's what the code does right now.
Honestly, using indexOf and equals is not really appropriate for this problem. indexOf is really only useful when you have something that's totally equal to the target you're looking for.
The best way to do something like this is
Optional<Stock> foundStock = list.stream().filter(stock -> stock.getName().equals(symbol)).findAny();
if (foundStock.isPresent()) {
// do something with foundStock.get()
} else {
// no found stock
}
indexOf() is a method return the index of the first occurrence of the specified element in the returned list. If the list does not contain this element, value -1 is returned.
More formally, return the lowest index i that meets the following conditions:
if(o==null? get(i)==null :o.equals(get(i))){
return i;
}
return -1;
If there is no such index, return -1.
And you have override the equals method, I guess you just want to focus on the same price Stock?:
#Override
public boolean equals(Object obj){
if (obj instanceof Stock){
Stock other = (Stock) obj;
return getPrice() == other.getPrice();
}
return false;
}
As my opinion, you have use List<Stock> list so the Object in the list is all Stock. Maybe it could be simplifed:
#Override
public boolean equals(Object obj){
Stock other = (Stock) obj;
return getPrice() == other.getPrice();
}
So, I'm initializing these instances and using the methods in the classes to modify the values. When I print the values within the method modifying them, they print correctly but when they are passed to the "toString" method they print the initial values instead of the modified values.
package com.meritamerica.assignment1;
public class AccountHolder {
/** Bank Account Information */
public String firstName, middleName, lastName, ssn;
public double checkingAccountOpeningBalance, savingsAccountOpeningBalance;
/** Default Constructor */
AccountHolder(){
}
/** Custom Constructor */
AccountHolder
(String firstName,
String middleName,
String lastName,
String ssn,
double checkingAccountOpeningBalance,
double savingsAccountOpeningBalance)
{
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
this.ssn = ssn;
this.checkingAccountOpeningBalance = checkingAccountOpeningBalance;
this.savingsAccountOpeningBalance = savingsAccountOpeningBalance;
}
/** Getters and Setters */
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return this.middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getSSN() {
return this.ssn;
}
public void setSSN(String SSN) {
this.ssn = ssn;
}
public CheckingAccount getCheckingAccount() {
CheckingAccount temp = new CheckingAccount(checkingAccountOpeningBalance);
return temp;
}
public SavingsAccount getSavingsAccount() {
SavingsAccount temp = new SavingsAccount(savingsAccountOpeningBalance);
return temp;
}
/** Converts type to String */
#Override
public String toString() {
return "Name: " + this.firstName + " " + this.middleName + " " + this.lastName + "\r\n" +
"SSN: " + ssn + "\r\n" +
"Checking Account Balance: " + this.checkingAccountOpeningBalance + "\r\n" +
"Savings Account Balance " + this.savingsAccountOpeningBalance + "\r\n";
}
}
package com.meritamerica.assignment1;
public class CheckingAccount {
public double openingBalance, interestRate, futureBalance;
CheckingAccount(
double openingBalance)
{
this.openingBalance = openingBalance;
this.interestRate = 0.0001;
}
public double getBalance() {
return this.openingBalance;
}
public double getInterestRate() {
return this.interestRate;
}
public boolean withdraw(double amount) {
if(amount < openingBalance && amount > 0) {
openingBalance -= amount;
return true;
}else {
System.out.println("Not enough money!!!");
return false;
}
}
public boolean deposit(double amount) {
if(amount > 0) {
openingBalance += amount;
return true;
}else {
System.out.println("Cannot deposit a negative amount");
return false;
}
}
public double futureValue(int years) {
futureBalance = (openingBalance * Math.pow(1.0 + interestRate, years));
return futureBalance;
}
#Override
public String toString() {
return "Checking Account Balance: " + getBalance() + "\r\n" +
"Checking Account Interest Rate: " + getInterestRate() + "\r\n" +
"Checking Account Balance in 3 years " + futureValue(3);
}
}
package com.meritamerica.assignment1;
public class SavingsAccount {
public double openingBalance, interestRate, futureBalance;
SavingsAccount(
double openingBalance)
{
this.openingBalance = openingBalance;
this.interestRate = 0.01;
}
public double getBalance() {
return this.openingBalance;
}
public double getInterestRate() {
return this.interestRate;
}
public boolean withdraw(double amount) {
if(amount < openingBalance && amount > 0) {
openingBalance -= amount;
return true;
}else {
System.out.println("Not enough money!!!");
return false;
}
}
public boolean deposit(double amount) {
if(amount > 0) {
openingBalance += amount;
return true;
}else {
System.out.println("Cannot deposit a negative amount");
return false;
}
}
public double futureValue(int years) {
futureBalance = (openingBalance * Math.pow(1.0 + interestRate, years));
return futureBalance;
}
#Override
public String toString() {
return "Checking Account Balance: " + this.openingBalance + "\r\n" +
"Checking Account Interest Rate: " + this.interestRate + "\r\n" +
"Checking Account Balance in 3 years " + this.futureBalance;
}
}
package com.meritamerica.assignment1;
public class MeritAmericaBankApp {
public static void main(String[] args) {
AccountHolder john = new AccountHolder
("John",
"James",
"Doe",
"123-45-6789",
100.0,
1000.0);
System.out.println(john);
john.getCheckingAccount().deposit(500.0);
john.getCheckingAccount().withdraw(800.0);
john.getCheckingAccount().futureValue(3);
System.out.println(john.getCheckingAccount());
System.out.println(john.getSavingsAccount());
You are creating a new CheckingAccount and SavingsAccount objects each time you call getCheckingAccount and getSavingsAccount.
Create a CheckingAccount and SavingsAccount object in the AccountHolder constructor and use it.
CheckingAccount checkingAccount;
SavingsAccount savingsAccount;
AccountHolder (String firstName, String middleName, String lastName, String ssn,
double checkingAccountOpeningBalance,
double savingsAccountOpeningBalance) {
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
this.ssn = ssn;
this.checkingAccount = new CheckingAccount(checkingAccountOpeningBalance);
this.savingsAccount = new CheckingAccount(savingsAccountOpeningBalance);
}
public CheckingAccount getCheckingAccount() {
return checkingAccount;
}
public SavingsAccount getSavingsAccount() {
return savingsAccount;
}
**
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("********WELCOME TO CUSTOMER DETAIL**********");
System.out.println("");
BankAccount customerDetails = new BankAccount();
customerDetails.setAccountNumber(527553054);
System.out.println("Account Number : " + customerDetails.getAccountNumber());
customerDetails.setBalance(300000.00);
System.out.println("Balance : " + customerDetails.getBalance());
customerDetails.setCustomerName("Anish Shrestha");
System.out.println("Customer Name : " + customerDetails.getCustomerName());
customerDetails.setEmail("blah#gmail.com");
System.out.println("Email : " + customerDetails.getEmail());
customerDetails.setPhoneNumber(980709277);
System.out.println("Phone Number : "+ customerDetails.getPhoneNumber());
System.out.println("");
System.out.println("*********************");
BankAccount deposit = new BankAccount();
deposit.depositFunds(566);
}
}
package learnJava;
public class BankAccount {
public void depositFunds(double depositAmount) {
this.balance += depositAmount;
System.out.println("The total sum of money : " + this.balance);
}
private long accountNumber ;
private double balance;
private String customerName;
private String email;
private long phoneNumber;
//SETTER
public void setAccountNumber(long accountNumber) {
this.accountNumber = accountNumber;
}
public void setBalance(double balance) {
this.balance = balance;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public void setEmail(String email) {
this.email = email ;
}
public void setPhoneNumber(long phoneNumber) {
this.phoneNumber = phoneNumber ;
}
//GETTER
public long getAccountNumber() {
return this.accountNumber;
}
public double getBalance() {
return this.balance;
}
public String getCustomerName() {
return this.customerName;
}
public String getEmail() {
return this.email;
}
public long getPhoneNumber() {
return this.phoneNumber;
}
}
**
i could not add up deposit Amount to main balance
Is it due to the setter/getter or there is something wrong in my code......
I am beginner so help me out guysss.....
I am not able to access the data of getter
What could be the problem or is it a rule?
I have copy-paste your code, there is no problem. In comment, the output :
BankAccount deposit = new BankAccount();
deposit.depositFunds(100); // The total sum of money : 100.0
deposit.depositFunds(100); // The total sum of money : 200.0
System.out.println(deposit.getBalance()); // 200.0
I have one abstract class Account and one subclass SavingsAccount, but when I create SavingsAccount object it doesn't assign a number like 1001, 1002, 1003 and so on. Any idea why?
import java.util.ArrayList;
public abstract class Account {
private String accountType;
private static double balance = 0;
private static int accountId;
private static int accountNumberCounter = 1000;
private ArrayList<Account> accounts;
public Account(String acType, int acNumber){
accountType = acType;
accountNumberCounter ++;
accountId = accountNumberCounter;
}
public Account() {
accountNumberCounter++;
accountId = accountNumberCounter;
}
public void addAccounts(Account acc){
accounts.add(acc);
}
public void deposit(double amount){
balance += amount;
}
public abstract boolean withdraw(double value);
public String getAccountInfo(){
return "Account type: " + accountType + ", Account number: " + accountId;
}
public int getAccountNumber(){
return accountId;
}
public String getAccount(){
String accountInformation = "Account Number: : " + accountId + "\nAccount Type: " + accountType;
return accountInformation;
}
public void closeCurrentAccount() {
if (balance < 0) {
System.out.println("Your balance: " + balance + "Close your debt");
} else {
System.out.println("Ending balance: " + balance);
}
}
}
And this is SavingsAccount
public class SavingsAccount extends Account {
private static double balance = 0;
private static final double RATE = 1.0;
private static String accountType = "Savings Account";
private static int accountId;
public SavingsAccount(){
super();
}
public double getBalance(){
return balance;
}
public void deposit(double amount){
balance = balance + amount;
}
public boolean withdraw(double amount){
if (balance<= amount){
System.out.println("You have only" + amount + "left on your account.");
return false;
}
else{
balance -= amount;
System.out.println("You put:" + amount);
return true;
}
}
public static String getAccountType(){
return accountType;
}
public static double getRate(){
return RATE;
}
public static double calculateRate(){
return balance += (balance * RATE) / 100;
}
public String getAccount(){
String accountInformation = "Account Number: : " + accountId + "\nAccount Type: " + accountType +
"\nBalance: " + balance + "\nRate: " + RATE;
return accountInformation;
}
}
Maybe it's not needed but here is Customer class as well
import java.util.ArrayList;
public class Customer {
private String name;
private String surname;
private String personalNumber;
private ArrayList<Account> accounts;
public Customer(String customerName, String customerSurname, String customerPersonalNumber)
{
name = customerName;
surname = customerSurname;
personalNumber = customerPersonalNumber;
this.accounts = new ArrayList<Account>();
}
public Customer(){
}
public String getName(){
return name;
}
public String getSurname(){
return surname;
}
public String getPersonalNumber(){
return personalNumber;
}
public void setName(String aName){
name = aName;
}
public void setSurname(String aSurname){
surname = aSurname;
}
public void setPersonalNumber(String aPersonalNumber){
personalNumber = aPersonalNumber;
}
public void addAccounts(Account acc){
accounts.add(acc);
}
public String getCustomerInfo(){
return name + " " + surname + " " + personalNumber;
}
public int getFirstAccountNumber(){
return accounts.get(0).getAccountNumber();
}
public int getLastAccountNumber(){
return accounts.get(accounts.size()-1).getAccountNumber();
}
public ArrayList<Account> getAllAccounts(){
return accounts;
}
}
When I do some tests this unique number doesn't get assigned.
Is it something wrong with a constructor?
You marked accountId as static as well, so every instance of Account will acquire the same id, that is the latest you "generated".
Just mark accountId as a normal instance variable (i.e., remove static).
As a side note, re-declaring accountId in SavingsAccount breaks encapsulation and is, frankly, weird. You inherited getAccountNumber() from Account. Use that instead of accessing accountId directly. You're treating it as a read-only variable anyway.
I'm creating a java project named Bank. SavingsAccount and CurrentAccount classes are subclasses of Account class. In a class Bank, which stores an information about accounts I have to create a method which prints the sum of balance amount for all SAVINGS accounts. How should I write the method to sum exactly a balance of savings accounts, not of both savings and current accounts?
import java.util.ArrayList;
public class Bank
{
private ArrayList<Account> accounts;
public Bank()
{
super();
accounts = new ArrayList<Account>();
}
public void addAccount(Account theAccount)
{
accounts.add(theAccount);
}
public void getDescription()
{
for(Account account: accounts)
{
System.out.println("Name: " + account.getOwnerName() + "\nCode: " + account.getCode() + "\nBalance: " + account.getBalance());
}
}
public double accountsSum()
{
double total = 0;
for(Account acc: accounts)
{
total += acc.getBalance();
}
return total;
}
public void printSavingsBalance()
{
//?????
}
}
public class Account
{
protected String code;
protected String ownerName;
protected double balance;
public Account(String code,String ownerName, double balance)
{
this.code = code;
this.ownerName = ownerName;
this.balance = balance;
}
public String getCode(){return code;}
public String getOwnerName(){return ownerName;}
public double getBalance(){return balance;}
public void setBalance(double newBalance)
{
balance = newBalance;
}
public void addMoney(double plusMoney)
{
balance += plusMoney;
}
public void withdrawMoney(double minusMoney)
{
balance -= minusMoney;
}
}
public class SavingsAccount extends Account
{
private int term;
private double interestRate;
public SavingsAccount(int term, double interestRate, String code, String ownerName, double balance)
{
super(code,ownerName,balance);
this.term = term;
this.interestRate = interestRate;
}
public int getTerm(){return term;}
public double getInterestRate(){return interestRate;}
public void setTerm(int newTerm)
{
term = newTerm;
}
public void setInterestRate(double newInterestRate)
{
interestRate = newInterestRate;
}
public double interestSize()
{
return balance*interestRate/365*term;
}
}
You can use the instanceof to determine the type of the object and sum only when the type is Savings.
int totalBalance = 0;
for(Account account: accounts){
if (account instanceof Saving) {
totalBalance = totalBalance + account.getBalance();
}
}
private List<SavingsAccount> savingsAccounts;
private List<CurrentAccount> currentAccounts;
public addAccount(SavingsAccount account){
}
public addAccount(CurrentAccount account){
}
This would be much better to do. Then just iterate over the savings accounts and add the balance of all accounts. Introducing accountType and instanceof checks would be against polymorphism IMHO.
A much cleaner approach with Visitor pattern:
public class Bank{
private List<Account> accounts = new ArrayList<Account>();
public void add(Account account) {
accounts.add(account);
}
public double getBalance(){
AdditionAccountVisitor visitor = new AdditionAccountVisitor();
for(Account account : accounts){
account.accept(visitor);
}
return visitor.getSum();
}
}
abstract class Account{
private double balance;
public Account(double balance) {
this.balance = balance;
}
public double getBalance(){
return balance;
}
public abstract void accept(AccountVisitor visitor);
}
class SavingsAccount extends Account{
public SavingsAccount(double balance) {
super(balance);
}
#Override
public void accept(AccountVisitor visitor) {
visitor.visit(this);
}
}
class CurrentAccount extends Account{
public CurrentAccount(double balance) {
super(balance);
}
#Override
public void accept(AccountVisitor visitor) {
visitor.visit(this);
}
}
interface AccountVisitor{
public void visit(SavingsAccount savingsAccount);
public void visit(CurrentAccount savingsAccount);
}
class AdditionAccountVisitor implements AccountVisitor{
private double sum = 0.0;
#Override
public void visit(SavingsAccount savingsAccount) {
sum += savingsAccount.getBalance();
}
#Override
public void visit(CurrentAccount savingsAccount) {
//do nothing
}
public double getSum(){
return sum;
}
}
add an accountType field to the Account class, possibly of type enumeration (but also int etc). Then in the loop check if the account is of the desired type before adding the balance.
public void printSavingsBalance()
{
double total = 0;
for(Account acc: accounts)
{
if (acc.getType() == SAVINGS)
total += acc.getBalance();
}
return total;
}
or use 2 lists as suggested by #Narendra Pathai - depends on what else you want to do with the accounts and list
If you're emotionally distraught at the thought of using instanceof, add a virtual method to your superclass and define it thusly in each subclass:
Savings:
String accountType() {
return "Savings";
}
Checking:
String accountType() {
return "Checking";
}