ATM Machine customers.txt file - java

I'm a new user in stack overflow.. okay so I'm doing an ATM Java program.. my problem is, I'm having a hard time trying to figure out how to make a file reader (mine is customers.txt) in my ATMSimulator.java..
Here is my ATM.java :
/*
An ATM that accesses a bank.
*/
public class ATM
{
public static final int CHECKING = 1;
public static final int SAVINGS = 2;
private int state;
private int customerNumber;
private Customer currentCustomer;
private BankAccount currentAccount;
private Bank theBank;
public static final int START = 1;
public static final int PIN = 2;
public static final int ACCOUNT = 3;
public static final int TRANSACT = 4;
/*
Construct an ATM for a given bank.
#param aBank the bank to which this ATM connects
*/
public ATM (Bank aBank)
{
theBank = aBank;
reset();
}
/*
Resets the ATM to the initial state
*/
public void reset()
{
customerNumber = -1;
currentAccount = null;
state = START;
}
/*
Sets the current customer number and sets state to PIN.
(Precondition: state is START)
#param number the customer number
*/
public void setCustomerNumber (int number)
{
assert state == START;
customerNumber = number;
state = PIN;
}
/*
Finds customer in bank. If found, sets state to ACCOUNT, else to START
(Precondition: state is PIN)
#param pin the PIN of the current customer
*/
public void selectCustomer (int pin)
{
assert state == PIN;
currentCustomer = theBank.findCustomer (customerNumber, pin);
if (currentCustomer == null)
state = START;
else
state = ACCOUNT;
}
/*
Sets current account to checking or savings. Sets state to TRANSACT.
(Precondition: state is ACCOUNT or TRANSACT)
#param account one of CHECKING or SAVINGS
*/
public void selectAccount (int account)
{
assert state == ACCOUNT || state == TRANSACT;
if (account == CHECKING )
currentAccount = currentCustomer.getCheckingAccount ();
else
currentAccount = currentCustomer.getSavingsAccount();
state = TRANSACT;
}
/*
Withdraws amount from current account.
(Precondition state is TRANSACT)
#param value the amount to withdraw
*/
public void withdraw (double value)
{
assert state == TRANSACT;
currentAccount.withdraw(value);
}
/*
Deposits amount to current account.
(Prcondition: state is TRANSACT)
#param value the amount to deposit
*/
public void deposit (double value)
{
assert state == TRANSACT;
currentAccount.deposit (value);
}
/*
Gets the balance of the current account.
(Precondition: state is TRANSACT)
#return the balance
*/
public double getBalance()
{
assert state == TRANSACT;
return currentAccount.getBalance();
}
/*
Moves back to previous state
*/
public void back ()
{
if (state == TRANSACT)
state = ACCOUNT;
else if (state == ACCOUNT)
state = PIN;
else if (state == PIN)
state = START;
}
/*
Gets the current state of this ATM.
#return the currnt state
*/
public int getState ()
{
return state;
}
}
Here is my Customer.java :
/*
A bank customer with a checking and a savings account.
*/
public class Customer
{
private int customerNumber;
private int pin;
private BankAccount checkingAccount;
private BankAccount savingsAccount;
/*
Construct a customer with a given number and PIN.
#param aNumber the customer number
#param aPin the personal identification number
*/
public Customer (int aNumber, int aPin)
{
customerNumber = aNumber;
pin = aPin;
checkingAccount = new BankAccount();
savingsAccount = new BankAccount();
}
/*
Test if this customer matches a customer number and PIN
#param aNumber a customer number
#param aPin a personal identification number
#return true if the customer number and PIN match
*/
public boolean match (int aNumber, int aPin)
{
return customerNumber == aNumber && pin == aPin;
}
/*
Gets the checking account of this customer
#return the checking account
*/
public BankAccount getCheckingAccount()
{
return checkingAccount;
}
/*
Get the savings account of this customer
#return checking account
*/
public BankAccount getSavingsAccount()
{
return savingsAccount;
}
}
Here is my Bank.java :
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
/*
A bank contains customer with bank accounts
*/
public class Bank
{
private ArrayList<Customer> customers;
/*
Construct a bank with no customers
*/
public Bank()
{
customers = new ArrayList<Customer> ();
}
/*
Reads the customer numbers and pins
and initializes the bank accounts
#param filename the name of the customer file
*/
public void readCustomers(String filename)
throws IOException
{
Scanner in = new Scanner (new File(filename));
while (in.hasNext())
{
int number = in.nextInt();
int pin = in.nextInt();
Customer c = new Customer (number, pin);
addCustomer (c);
}
in.close();
}
/*
Adds a customer to the bank.
#param c the customer to add
*/
public void addCustomer (Customer c)
{
customers.add(c);
}
/*
Find a customer in the bank.
#param aNumber a customer number
#param aPin a personal identification number
#return the matching customer, or null if no customer matches
*/
public Customer findCustomer (int aNumber, int aPin)
{
for (Customer c : customers)
{
if (c.match(aNumber, aPin))
return c;
}
return null;
}
}
Here is my BankAccount.java :
/**
A bank account has a balance that can be changed by deposits and withdrawals
*/
public class BankAccount
{
private int accountNumber;
private double balance;
/**
Counstruct a bank account with a zero balance.
#param anAccountNumber the account number for this account
*/
public BankAccount(){}
public BankAccount(int anAccountNumber)
{
accountNumber = anAccountNumber;
balance = 0;
}
/**
Construct a bank account with a given balance.
#param anAccountNumber the account number for this account
#param initialBalance the initial balance
*/
public BankAccount(int anAccountNumber, double initialBalance)
{
accountNumber = anAccountNumber;
balance = initialBalance;
}
/**
Gets the account number of this bank account.
#return the account number
*/
public int getAccountNumber()
{
return accountNumber;
}
/**
Deposits money into bank account
#param amount the amount to deposit
*/
public void deposit (double amount)
{
double newBalance = balance + amount;
balance = newBalance;
}
/**
Withdraws money from the bank account.
#param amount the amount to withdraw
*/
public void withdraw(double amount)
{
double newBalance = balance - amount;
balance = newBalance;
}
/**
Gets the current balance of the bank account.
#return the current balance
*/
public double getBalance()
{
return balance;
}
}
And I'm having a problem with customers.txt in ATMSimulator.java:
import java.io.IOException;
import java.util.Scanner;
/*
A text based simulation of an automatic teller machine.
*/
public class ATMSimulator
{
public static void main (String [] args)
{
ATM theATM;
try
{
Bank theBank = new Bank ();
theBank.readCustomers("customers.txt");
theATM = new ATM (theBank);
}
catch (IOException e)
{
System.out.println ("Error opening accounts file.");
return;
}
Scanner in= new Scanner (System.in);
while (true)
{
int state = theATM.getState();
if (state == ATM.START)
{
System.out.print ("Enter customer number: ");
int number = in.nextInt();
theATM.setCustomerNumber(number);
}
else if (state == ATM.PIN)
{
System.out.println ("Enter PIN: ");
int pin = in.nextInt();
theATM.setCustomerNumber (pin);
}
else if (state == ATM.ACCOUNT )
{
System.out.print ("A = Checking, B = Savings, C = Quit: ");
String command = in.next();
if (command.equalsIgnoreCase ("A"))
theATM.selectAccount (ATM.CHECKING);
else if (command.equalsIgnoreCase ("B"))
theATM.selectAccount (ATM.SAVINGS);
else if (command.equalsIgnoreCase ("C"))
theATM.reset();
else
System.out.println ("Illegal input!");
}
else if (state == ATM.TRANSACT)
{
System.out.println ("Balance = " + theATM.getBalance());
System.out.print ("A = Deposit, B = Withdrawal, C = Cancel: ");
String command = in.next();
if (command.equalsIgnoreCase ("A"))
{
System.out.print ("Amount: ");
double amount = in.nextDouble();
theATM.deposit (amount);
theATM.back();
}
else if (command.equalsIgnoreCase ("B"))
{
System.out.print ("Amount: ");
double amount = in.nextDouble();
theATM.withdraw (amount);
theATM.back();
}
else if (command.equalsIgnoreCase ("C"))
theATM.back();
else
System.out.println ("Illegal input!");
}
}
}
}
I had created the customers.txt file, but the output is error.. please help me

I'll address your question not the sh.. big amount of code.
You efficiently read from file in this way.
try( BufferedReader br = new BufferedReader(new FileReader("filename.txt"))){
String line;
while((line = br.readLine()) != null){
}
}catch(IOException e}{
e.printStackTrace();
}
If you wish to read from console:
try( BufferedReader br = new BufferedReader(new InputStreamReader(System.in))){
String line;
while((line = br.readLine()) != null){
}
}catch(IOException e}{
e.printStackTrace();
}
To indicate the end of input in the console use ctrl + z.

Hey so the path for the text file you passed in the method readCustomer is not the right path. So what you can do is put in src and package name in the path as follows: "src/packageName/customer.txt"
so when you call it in your main it would be
public static void main (String [] args)
{
ATM theATM;
try
{
Bank theBank = new Bank ();
theBank.readCustomers("src/packageName/customer.txt");
theATM = new ATM (theBank);
}
Hope this helps.

Related

Appears that java is replacing my objects over another, how can I remedy this [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
The project is to create an application that models an ice cream shop, tracking the number of cartons opened and allowing two different scoop sizes, the professor wants it all split up into classes like I have it.
This is my main method, which creates and calls my scoop class.
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
//Creating Objects
Scanner input = new Scanner(System.in);
Scoop scoop = new Scoop();
IceCreamShoppe icecreamshoppe = new IceCreamShoppe();
//Prompting user to define sizes of scoops and carton
System.out.println("How big is the first ice cream scoop?(radius in cm's)");
scoop.setScoop1(input.nextDouble());
System.out.println("How big is the second ice cream scoop?(radius in cm's)");
scoop.setScoop2(input.nextDouble());
System.out.println("How big is the ice cream carton?(radius in cm's)");
icecreamshoppe.setCarton_radius(input.nextDouble());
System.out.println("How big is the ice cream carton?(height in cm's)");
icecreamshoppe.setCarton_height(input.nextDouble());
//Returns to user their set values and sets size of carton
System.out.printf("Scoop 1: %.2f, Scoop 2: %.2f, Carton Radius: %.2f, Carton Height %.2f%n", scoop.getScoop1(), scoop.getScoop2(), icecreamshoppe.getCarton_radius(), icecreamshoppe.getCarton_height());
//While statement that continuously prompts user which scoop they want to use, everything else is done in the IceCreamShoppe Class
while(true) {
System.out.println("Which scoop would you like to use? (1 or 2) (0 = Exit)");
int scoopNumber = input.nextInt();
System.out.println("How many scoops would you like?");
int scoopCount = input.nextInt();
icecreamshoppe.serve(scoopNumber, scoopCount);
}//end while
}//end main
}//class
Here is my scoop method, that calls itself, I think this is the root of the problem. The problem is that my scoop sizes keep on getting reset whenever I call the scoop class.
public class Scoop {
//Instance Variables
private double volume;
private double scoop1;
private double scoop2;
//Constructors
public double doScoop(int r) {
System.out.printf("You want this%f", this.getScoop1());
if(r == 1) {
volume = (Math.PI)*Math.pow(this.getScoop1(), 3)*(4.0/3.0);
this.setVolume(volume);
System.out.printf("%f", volume);
return volume;
}
else if(r == 2) {
volume = (Math.PI)*Math.pow(this.getScoop2(), 3)*(4.0/3.0);
this.setVolume(volume);
System.out.printf("%f", volume);
return volume;
}
else {
System.out.println("Invalid Scoop Number!");
return 0;
}
}
/**
* #return the volume
*/
public double getVolume() {
return volume;
}
/**
* #param volume the volume to set
*/
public void setVolume(double volume) {
this.volume = volume;
}
/**
* #return the scoop1
*/
public double getScoop1() {
return scoop1;
}
/**
* #param scoop1 the scoop1 to set
*/
public void setScoop1(double scoop1) {
this.scoop1 = scoop1;
}
/**
* #return the scoop2
*/
public double getScoop2() {
return scoop2;
}
/**
* #param scoop2 the scoop2 to set
*/
public void setScoop2(double scoop2) {
this.scoop2 = scoop2;
}
//
}//end class
Here are the other two classes, I dont think they are the problem, but then again, what do I know?
import java.util.Scanner;
public class IceCreamShoppe {
//Instance Variables
private double carton_radius;
private double carton_height;
private int cartons_used = 0;
//Constructors
public IceCreamShoppe() {
}
public IceCreamShoppe(double r, double h) {
this.setCarton_radius(r);
this.setCarton_height(h);
}
public int carton_used() {
this.setCartons_used(this.getCartons_used() + 1);
return this.getCartons_used();
}
/*
* Object to serve the ice cream, the only input is which scoop is supposed to be used.
* #param s Sets the
*/
public boolean serve(int s, int n) {
Scanner input = new Scanner(System.in);
Scoop scoop = new Scoop();
Carton carton = new Carton();
int i = 0;
//Checks which scoop the is being used
if(s != 0) {
double scoopVolume = scoop.doScoop(1);
while(i <= n) {
if((boolean) carton.hasEnough(scoopVolume)) {
carton.remove(scoopVolume);
System.out.println(carton.getContains());
i++;
}
else {
this.carton_used();
carton.carton(this.getCarton_radius(), this.getCarton_height());
carton.remove(scoopVolume);
System.out.printf("Carton Empty, Total Cartons Used:%d%n", this.getCartons_used());
System.out.printf("New carton contains: %.2f%n", carton.getContains());
}
}
}
else {
System.out.printf("You have used %d cartons of ice cream, there is %.2f ice cream remaining in the current carton", this.getCartons_used(), carton.getContains());
return false;
}
return true;
}
//Getters and Setters
/**
* #return the carton_radius
*/
public double getCarton_radius() {
return carton_radius;
}
/**
* #param carton_radius the carton_radius to set
*/
public void setCarton_radius(double carton_radius) {
this.carton_radius = carton_radius;
}
/**
* #return the carton_height
*/
public double getCarton_height() {
return carton_height;
}
/**
* #param carton_height the carton_height to set
*/
public void setCarton_height(double carton_height) {
this.carton_height = carton_height;
}
/**
* #return the cartons_used
*/
public int getCartons_used() {
return cartons_used;
}
/**
* #param cartons_used the cartons_used to set
*/
public void setCartons_used(int cartons_used) {
this.cartons_used = cartons_used;
}
}//End Class
public class Carton {
//Instance Variables
private double contains;
//Objects
//Checks if the carton has enough remaining, if not
public boolean hasEnough(double v) {
if ((this.getContains() - v) >= 0) {
return true;
}
else {
return false;
} }
//Sets the carton size
public void carton(double r, double h) {
this.setContains(Math.PI*Math.pow(r, 2)*h);
}
//After checking if there is enough ice cream, this will run, there is
no check against going negative
public void remove(double v) {
this.setContains(this.getContains() - v);
}
//Getters and Setters
/**
* #return the contains
*/
public double getContains() {
return contains;
}
/**
* #param contains the contains to set
*/
public void setContains(double contains) {
this.contains = contains;
}
}
You are not passing in your scoop object into your icecreamshoppe.serve method and then you are creating a new scoop object in your serve method.
You should pass it in:
icecreamshoppe.serve(scoopNumber, scoopCount, scoop);
and change your serve method as follows:
public boolean serve(int s, int n, Scoop scoop) {
Scanner input = new Scanner(System.in);
Carton carton = new Carton();
int i = 0;
//Checks which scoop the is being used
if(s != 0) {
double scoopVolume = scoop.doScoop(1)

Java Method not getting correct Value,

I was experimenting with a program idea and therefore have way to many classes, which very well could have been methods, however in my CF method (Don't worry about the naming conventions they were changed to post online) however, when I try to set cF to cF=getTi-getTe the values from the getters always print 0 but this is only in the calculate cF method. If I print the getters and setters in the main method alone they print out with the correct numbers.
public class CF {
private double cF;
Income rI= new Income();
Expenses e = new Expenses();
public double getCF() {
return cF;
}
public void setCF(double cF) {
this.cF = cF;
}
public CF(){
//cF=0;
}
public double calculateCF(){
cF= rI.getTi()-e.getTe();// this line will return 0 no matter what
return cF;
}
}
public class Expenses {
private double tExpenses,exp1,exp2;
public Expenses(){
tExpenses=exp1=exp2=0;
}
public double calculateTotalExpenses(){
tExpenses=exp1+exp2;
return tExpenses;
}
/**
* #return the tExpenses
*/
public double getTe() {// again don't worry about naming conventions //they are correct in the IDE
return tExpenses;
}
/**
* #param tExpenses the tExpenses to set
*/
public void setTe(double tExpenses) {
this.tExpenses = tExpenses;
}
}
public class RI {
private double rI;
private double incomeMisc;
private double tIncome;
public RI(){
rI=0;
incomeMisc=0;
tIncome=0;
}
public double calculateRI(){
tIncome= rI+incomeMisc;
return tIncome;
}
/**
* #return the incomeMisc
*/
public double getIncomeMisc() {
return incomeMisc;
}
/**
* #param incomeMisc the incomeMisc to set
*/
public void setIncomeMisc(double incomeMisc) {
this.incomeMisc = incomeMisc;
}
/**
* #return the tIncome
*/
public double gettIncome() {
return tIncome;
}
/**
* #param tIncome the tIncome to set
*/
public void settIncome(double tIncome) {
this.tIncome = tIncome;
}
}
public class FSAProgram {
public static void main(String[] args) {
RI rI = new RI();
Expenses e = new Expenses();
CF cF= new CF();
System.out.println("Enter RI");
Scanner k = new Scanner(System.in);
rI.I(k.nextDouble());
System.out.println("Enter Misc Income");
rI.setIncomeMisc(k.nextDouble());
rI.calculateRI();
System.out.println("Total Income is: "+ rI.getTi());
System.out.println("Enter expense");
e.setExp1(k.nextDouble());// I know this isn't correct its because // I changed the name to post this question
e.calculateTotalExpenses();
System.out.println("Total Expenses :"+ e.gettExpenses());
//cF.calculateCF();
System.out.println(""+(e.gettExpenses() +" "+ rI.gettIncome()));
// Prints fine when last statement is executed
//The next statement is what returns 0 unfortunately
System.out.println("CF: "+ cF.calculateCF());
}
}
Sample output
**Enter RI
2000
Enter Misc Income
0
Total Income is: 2000.0
Enter Exp1// these are a combination of other things in the actual program
900
Total Expenses :900.0
900 2000
CF 0.0
You just make two new objects without setting its value, sure it returns 0.
Income rI= new Income();
Expenses e = new Expenses();
To make it workable, here are hints:
//in your main
CF cF= new CF(rI, e);
//in your cf
private double cF;
private Income income;
private Expenses expense;
public CF(Income rI, Expense e){
this.income = rI;
this.expense = e;
}

Add & Print from List using Scanner

I am creating a project that allows a user to create, delete or display bank accounts and to deposit, withdraw or print transactions.
I don't know how to deposit, withdraw, print transactions using the scanner when the user provides the account id.
main:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
BankProcess bankProcess = new BankProcess();
TransactionProcess transactionProcess = new TransactionProcess();
Bank bank = new Bank();
BankAccount bankAccount = new BankAccount();
int input = 0;
int selection = 0;
while (input == 0) {
System.out.println("");
System.out.println("Please choose one of the following: ");
System.out.println("[1] Create an account");
System.out.println("[2] Print all existing accounts");
System.out.println("[3] Delete an account");
System.out.println("[4] Deposit");
System.out.println("[5] Withdraw");
System.out.println("[6] Print transactions");
System.out.println("[0] Exit");
selection = scan.nextInt();
switch (selection) {
case 0:
System.out.println("Exit Successful");
System.exit(0);
case 1:
System.out.println("'[1] Create an account' has been selected.");
System.out.print("Account Id: ");
int accountId = scan.nextInt();
scan.nextLine();
System.out.print("Holder Name: ");
String holderName = scan.nextLine();
System.out.print("Holder Address: ");
String holderAddress = scan.nextLine();
System.out.print("Opening Balance: ");
double openingBalance = scan.nextDouble();
System.out.print("Open Date: ");
String openDate = scan.next();
bankAccount = new BankAccount(accountId, holderName, openingBalance, holderAddress, openDate);
bank.setAccounts(bankProcess.openNewAccount(bank.getAccounts(), bankAccount));
System.out.println("Successfully Added.");
break;
case 2:
System.out.println("'[2] Display all existing accounts' has been selected");
System.out.println("-----------------------------------------------------");
bank.getAccounts().forEach((i, b) - > System.out.println(b));
System.out.println("-----------------------------------------------------");
break;
case 3:
System.out.println("[3] Delete an account has been selected");
System.out.println("Enter the account ID: ");
bank.removeAccounts(bankProcess.openNewAccount(bank.getAccounts(), bankAccount));
break;
case 4:
System.out.println("[4] Deposit has been selected");
break;
case 5:
System.out.println("[5] Withdraw has been selected");
break;
case 6:
System.out.println("[6] Print Transaction has been selected");
break;
default:
System.out.println("Your choice was not valid!");
}
}
}
class Bank
public class Bank {
private TreeMap < Integer, BankAccount > bankAccounts = new TreeMap < Integer, BankAccount > ();
public TreeMap < Integer, BankAccount > getAccounts() {
return bankAccounts;
}
public void setAccounts(TreeMap < Integer, BankAccount > accounts) {
this.bankAccounts = accounts;
}
public void removeAccounts(TreeMap < Integer, BankAccount > accounts) {
this.bankAccounts = accounts;
}
}
class BankProcess
public class BankProcess {
// return the Updated list of BankAccounts
public TreeMap < Integer, BankAccount > openNewAccount(TreeMap < Integer, BankAccount > bankAccounts, BankAccount bankAccount) {
//Get the List of existing bank Accounts then add the new BankAccount to it.
bankAccounts.put(bankAccount.getAccountId(), bankAccount);
return bankAccounts;
}
public TreeMap < Integer, BankAccount > removeAccount(TreeMap < Integer, BankAccount > bankAccounts, BankAccount bankAccount) {
bankAccounts.remove(bankAccount.getAccountId(), bankAccount);
return bankAccounts;
}
}
class BankAccount
public class BankAccount {
private int accountId;
private String holderName;
private String holderAddress;
private String openDate;
private double currentBalance;
private List < Transaction > transactions = new ArrayList < Transaction > ();
//Provide Blank Constructor
public BankAccount() {}
//Constructor with an arguments.
public BankAccount(int accountNum, String holderNam, double currentBalance, String holderAdd, String openDate) {
this.accountId = accountNum;
this.holderName = holderNam;
this.holderAddress = holderAdd;
this.openDate = openDate;
this.currentBalance = currentBalance;
}
// Always Provide Setter and Getters
public int getAccountId() {
return accountId;
}
public void setAccountId(int accountId) {
this.accountId = accountId;
}
public String getHolderName() {
return holderName;
}
public void setHolderName(String holderName) {
this.holderName = holderName;
}
public String getHolderAddress() {
return holderAddress;
}
public void setHolderAddress(String holderAddress) {
this.holderAddress = holderAddress;
}
public String getOpenDate() {
return openDate;
}
public void setOpenDate(String openDate) {
this.openDate = openDate;
}
public double getCurrentBalance() {
return currentBalance;
}
public void setCurrentBalance(double currentBalance) {
this.currentBalance = currentBalance;
}
public List < Transaction > getTransactions() {
return transactions;
}
public void setTransactions(List < Transaction > transactions) {
this.transactions = transactions;
}
public String toString() {
return "\nAccount number: " + accountId + "\nHolder's name: " + holderName + "\nHolder's address: " + holderAddress + "\nOpen Date: " + openDate + "\nCurrent balance: " + currentBalance;
}
}
class Transaction
public class Transaction {
private int transactionId;
private String transactionType;
private double transactionAmount;
private double moneyBeforeTransaction;
private double moneyAfterTransaction;
public Transaction() {}
public Transaction(int transactionId, String transactionType, double transactionAmount, double moneyBeforeTransaction) {
this.transactionId = transactionId;
this.transactionType = transactionType;
this.transactionAmount = transactionAmount;
this.moneyBeforeTransaction = moneyBeforeTransaction;
}
public int getTransactionId() {
return transactionId;
}
public void setTransactionId(int transactionId) {
this.transactionId = transactionId;
}
public String getTransactionType() {
return transactionType;
}
public void setTransactionType(String transactionType) {
this.transactionType = transactionType;
}
public double getTransactionAmount() {
return transactionAmount;
}
public void setTransactionAmount(double transactionAmount) {
this.transactionAmount = transactionAmount;
}
public double getMoneyBeforeTransaction() {
return moneyBeforeTransaction;
}
public void setMoneyBeforeTransaction(double moneyBeforeTransaction) {
this.moneyBeforeTransaction = moneyBeforeTransaction;
}
public double getMoneyAfterTransaction() {
return moneyAfterTransaction;
}
public void setMoneyAfterTransaction(double moneyAfterTransaction) {
this.moneyAfterTransaction = moneyAfterTransaction;
}
//Override the toString() method of String ?
public String toString() {
return "Transaction ID : " + this.transactionId +
" Transaction Type : " + this.transactionType +
" Transaction Amount : " + this.transactionAmount +
" Money Before Transaction : " + this.moneyBeforeTransaction +
" Money After Transaction : " + this.moneyAfterTransaction;
}
}
class TransactionProcess
public class TransactionProcess {
//Always Provide another class for process.
//Pass the bankAccount of the user
public void deposit(BankAccount bankAccount, double depositAmount) {
//Get the CurrentBalance
double currentBalance = bankAccount.getCurrentBalance();
//First Argument : set the Id of transaction
//Second Argument : set the Type of Transaction
//Third Argument : set the TransactionAmount
//Fourth Argument : set the Balance Before the transaction (for record purposes)
Transaction transaction = new Transaction(bankAccount.getTransactions().size(), "Deposit", depositAmount, currentBalance);
if (depositAmount <= 0) {
System.out.println("Amount to be deposited should be positive");
} else {
//Set the updated or transacted balance of bankAccount.
bankAccount.setCurrentBalance(currentBalance + depositAmount);
//then set the MoneyAfterTransaction
transaction.setMoneyAfterTransaction(bankAccount.getCurrentBalance());
//after the transaction add it to the list of Transaction of bankAccount
bankAccount.getTransactions().add(transaction);
}
}
// Explanation same as above
public void withdraw(BankAccount bankAccount, double withdrawAmount) {
double currentBalance = bankAccount.getCurrentBalance();
Transaction transaction = new Transaction(bankAccount.getTransactions().size(), "Withdraw", withdrawAmount, currentBalance);
if (withdrawAmount <= 0) {
System.out.println("Amount to be withdrawn should be positive");
} else {
if (currentBalance < withdrawAmount) {
System.out.println("Insufficient balance");
} else {
bankAccount.setCurrentBalance(currentBalance - withdrawAmount);
transaction.setMoneyAfterTransaction(bankAccount.getCurrentBalance());
bankAccount.getTransactions().add(transaction);
}
}
}
}
Operations like deposit or withdraw work almost the same way, so let's concentrate on deposit for now.
You already have the appropriate switch-case for that:
case 4: {
// deposit
break;
}
(by the way: the braces { and } are not mandatory here, they just help to isolate the code, so that it is easier to read)
Anyway; For deposing money on a bank account you need the account number first and then you need to get the account from the bank
case 4: {
int accountNumber = scan.nextInt(); // user types account number
TreeMap <Integer, BankAccount> bankAccounts = bank.getAccounts(); // bank returns all accounts (this is quite an insecure operation, it would be better to add a method to the bank class that returns only one account when passing the accountNumber
BankAccount bankAccount = bankAccounts.get(accountNumber);
break;
}
Using the method bank.getAccounts is not a good design here, as the method will return all accounts from the bank. It would be better to have a method in your class Bank that returns a single account.
public class Bank{
// ...
public BankAccount getAccount(Integer accountNumber){
return bankAccounts.get(accountNumber);
}
}
Because this will encapsulate the logic to retrieve one account to the Bank class. There you can also add some error handling logic, e.g. when the account number is not valid.
So, at this point you have the user's account and you know the user wants to deposit some money. You only have to ask how much he wants to deposit. Use the Scanner again to let the user type in an amount.
Now that you have your BankAccount and the amount you need to make a Transaction or better a TransactionProcess
TransactionProcess transactionProcess = new TransactionProcess(); // use the standard constructor to create an empty transactionProcess
transactionProcess.deposit(bankAccount, amount);
If I understand your program correctly, the method deposit will already use the user's BankAccount and add the money while creating a Transaction for the account. Am I correct? Then you are actually finished here.
Put that code together for switch-chase 4 and if it works use a similar logic to implement withdraw.
I hope this helps!
// Edit // to answer your other question, this is what I had in mind:
in your BankAccount class add a method like this one:
public void addTransaction(Transaction transaction){
if(transactions.size() >= 6){ // test if the list has 6 or more transactions saved
transactions.remove(0); // if so, then remove the first (it's the oldest)
}
transactions.add(transaction); // the new transaction is always added, no matter how many other transactions there are already in the list
}
This is just an example, but I think you should be able to control the amount of transactions per Bank account like this. In addition you can now simplify the call: have a look at the last line of your deposit method in your TransactionProcess class. There you call
bankAccount.getTransactions().add(transaction); // takes the bank account, retrieves the list of transactions from the bank account and adds a transaction to the list
with the new method addTransaction you could now write it like this instead:
bankAccount.addTransaction(transaction); // adds a transaction to the bank account
Much cleaner, don't you think? And now you can put all your logic for managing and adding transactions in that new method :)

calling methods from classes in the main method

I am a bit stuck on this one. I am writing a java program with two classes, and then a test program to test the methods in the class. I am stuck on calling the two methods below in the main method. All of the class files (the test program class and the two other classes) are compiling and the IDE is not giving me any error messages, the calculation is just not occurring...
--Main Method Code:
//Call debit method
System.out.println("Please enter amount to be debited");
double amount=input.nextDouble();
account.debit(amount);
System.out.printf("%.2f%n",balance);
//Call credit method
System.out.println("Please enter amount to be credited");
amount=input.nextDouble();
account.credit(amount);
System.out.printf("%.2f%n",balance);
--Account Class Code:
//Method for crediting account balance
public void credit (double amount) {
double newBalance=this.balance+amount;
this.setBalance(newBalance);
}
//Method for debiting account balance
public void debit (double amount) {
if (amount<balance) {
double newBalance=this.balance-amount;
this.setBalance(newBalance);
} else {
System.out.println("Insufficient Funds!");
}
NOTE: the balance setter is working, as it is called earlier in the test program...
Any help much appreciated!!!
Complete Code for Account Class:
public class Account {
private int accountId;
private String accountName;
private String accountAddress;
private double balance;
private Bank bank;
//Default Constructor
public Account () {
}
//Getters
public int getAccountId () {
return accountId;
}
public String getAccountName () {
return accountName;
}
public String getAccountAddress () {
return accountAddress;
}
public double getBalance () {
return balance;
}
public Bank getBank () {
return bank;
}
//Setters
public void setAccountId (int accountId) {
if (accountId <=10000000 || accountId >=99999999) {
System.out.println("Invalid Account Id");
} else {
this.accountId=accountId;
}
}
public void setAccountName (String accountName) {
if (accountName.length()>=10) {
System.out.println("Too Long");
} else {
this.accountName=accountName;
}
}
public void setAccountAddress (String accountAddress) {
this.accountAddress=accountAddress;
}
public void setBalance (double balance) {
if (balance<0.0) {
System.out.println("Invalid Balance");
} else {
this.balance=balance;
}
}
public void setBank (Bank bank) {
this.bank=bank;
}
//Constructor to initialize accountId, accountName, accountAddress and Bank
public Account (int accountId, String accountName, String accountAddress, Bank bank) {
this.setAccountId(accountId);
this.setAccountName(accountName);
this.setAccountAddress(accountAddress);
this.setBank(bank);
}
//Method to print out account category based on balance
public void printAccountCategory () {
if (balance<100.0) {
System.out.println("Challenged Account");
} else if (balance>=100.0 && balance<999.9) {
System.out.println("Standard Account");
} else if (balance>=1000.0 && balance<9999.9) {
System.out.println("Promising Account");
} else if (balance>=10000.0 && balance<99999.9) {
System.out.println("Gold Star Account");
} else {
System.out.println("Super Duper Account");
}
}
//Method to project balance based on compound interest and the number of years required
//Note: I took the formula using n (number of times the interest is compounded per year) as 1
public double projectNewBalance (int numberYears) {
if (numberYears>0) {
double interest=1;
for (int i=1; i<=numberYears; i++) {
interest*=(1.0+bank.getInterestRate());
}
double newBalance=balance*interest;
return newBalance;
} else if (numberYears<0) {
System.out.println("Invalid Value");
} else {
return balance;
}
return balance;
}
//Method for crediting account balance
public void credit (double amount) {
double newBalance=this.balance+amount;
this.setBalance(newBalance);
}
//Method for debiting account balance
public void debit (double amount) {
if (amount<balance) {
double newBalance=this.balance-amount;
this.setBalance(newBalance);
} else {
System.out.println("Insufficient Funds!");
}
}
//toString method
public String toString () {
return "Account Id: "+accountId+", Account Name: " + accountName + ", Account Address: "+accountAddress+", Balance: "+balance+", Bank Details: "+bank.toString()+".";
}
}
Main Method Full Code:
import java.util.Scanner;
public class BankAccountTest {
public static void main (String [ ] args) {
//Create an instance of the Bank class
Bank bank = new Bank ("WIT Bank", "Paddy Snow", 0.045);
//Create instance of Scanner class
Scanner input=new Scanner(System.in);
//Prompt user to input data to create an account
System.out.println("Please enter an Account ID");
int accountId=input.nextInt();
System.out.println("Please enter an Account Name");
String accountName=input.next();
System.out.println("Please enter an Account Address");
String accountAddress=input.next();
//Create instance of the Account class
Account account = new Account (accountId, accountName, accountAddress, bank);
//Print out details of account class
System.out.println(account);
//Prompt user to enter balance for the account
System.out.println("Please enter account balance");
double balance=input.nextDouble();
account.setBalance(balance);
//Use printAccountCategory method
account.printAccountCategory();
//Call projectNewBalance method
// Note: Method tested with value of 10 years as mentioned in spec,
// but user input also included I think it is more appropriate for the functionality of the program
// int numberYears=10;
// double newBalance1=account.projectNewBalance(numberYears);
// System.out.println(""+newBalance1);
System.out.println("Please enter number of years");
int numberYears=input.nextInt();
double newBalance=account.projectNewBalance(numberYears);
System.out.printf("%.2f%n",newBalance);
//Call debit method
System.out.println("Please enter amount to be debited");
double amount=input.nextDouble();
account.debit(amount);
System.out.printf("%.2f%n",balance);
//Call credit method
System.out.println("Please enter amount to be credited");
amount=input.nextDouble();
account.credit(amount);
System.out.printf("%.2f%n",balance);
}
}
Your numbers might always look the same because the local variable is not being updated before printing it out.
Make sure you update the value of balance before your call to System.out.printf("%.2f%n",balance);.
Something like:
balance = account.getBalance();
Shouldn't it be printing the balance of the object you have created and not just "balance":
System.out.println(account.getBalance())?

Create several new objects within a for-loop in Java

I want to create several objects from a class in a for loop. but I don't know how to code it. What I have written creates a new object but it overwrites the previous object.
package assginment1_version4;
import java.util.*;
public class Client {
public static void main (String[] args) {
System.out.println ("this is a bill database");
System.out.println ("add a user?(Y/N)");
Scanner input = new Scanner(System.in);
String answer = input.nextLine ();
ArrayList ary = new ArrayList ();
for (int i=1 ; i < 100; i++) {
if (answer.equalsIgnoreCase("y")) {
Bill bill1 = new Bill();
System.out.println("user first name:");
bill1.setFname (input.nextLine());
System.out.println("user Last name:");
bill1.setLname (input.nextLine());
System.out.println ("add a user?(Y/N)");
answer = input.nextLine ();
} else if (answer.equalsIgnoreCase ("n")) {
if (Bill.getBillCounter () == 0) {
System.out.println ("the Database is empty");
break;
} else {
System.out.println ("Number of Users: "
+ Bill.getBillCounter ());
break;
}
} else {
while (!answer.equalsIgnoreCase ("n")
&& !answer.equalsIgnoreCase ("y")) {
System.out.println ("add a user?(Y/N)");
answer = input.nextLine ();
}
}
}
}
}
please help me to complete this code.
You're overriding them because you create a new Bill on each loop and never save them off anywhere. I believe you want to add them to your ArrayList:
First, you should add a type to your ArrayList:
ArrayList<Bill> ary = new ArrayList<Bill>();
Then, before you get the input from the user on whether or not to add a new Bill, you should add the current one to this list:
...
System.out.println("user Last name:");
bill1.setLname(input.nextLine());
ary.add(bill1);
...
You haven't used the ArrayList, you need to add the Bill's objects at the end of the for loop.
ary.add(bill1);
and add a type to your ArrayList
ArrayList<Bill> ary = new ArrayList<Bill>();
This is the Bill class.....
package assginment1_version2;
public class Bill {
/**
* Attributes of a bill
*/
private String firstName;
private String lastName;
private int paymentDeadline;
private int paymentCode;
private int billCode;
/**
* Attribute of Bill Class
*/
private static int BillCounter=0;
/**
* Methods of Bill class
* #return number of users
*/
/*public static int getBillCounter(){
return BillCounter;
}*/
/**
* Class Constructor
* #param Fname is the first name of user
* #param Lname is the last name of user
* #param Pdeadline is the deadline of paying the bill
* #param Pcode introduces the payment uniquely
* #param Bcode introduces the bill uniquely
*/
public Bill (){
BillCounter++;
}
/**
* FirstName methods
* method to set FirstName
* #param n is the input of setname method as a user name
*/
public void setFname (String n){
firstName=n;
}
// method to get FirstName
public String getFname (){
return firstName;
}
/**
* LastName methods
* method to set LastName
*/
public void setLname (String m){
lastName=m;
}
// method to get LastName
public String getLname(){
return lastName;
}
/**
* PaymentDeadline methods
* method to set PaymentDeadline
*/
public void setPaymentDeadline(int m){
paymentDeadline= m;
}
//method to get PaymentDeadline
public int getPaymentDeadline(){
return paymentDeadline;
}
/*
* PaymentCode methods
* Method to set PaymentCode
*/
public void setPaymentCode (int m){
paymentCode=m;
}
//method to get PaymentCode
public int getPaymentCode(){
return paymentCode;
}
/*
* Methods of BillCode
* method to set BillCode
*/
public void setBcode(int Bcode){
billCode=Bcode;
}
//method to get BillCode
public int getBcode(){
return billCode;
}
}

Categories

Resources