I have a BankAccount class that models bank account information and a main method that is supposed to create an array list of BankAccount objects from user input and then write that info to a text file.
Here's my BankAccount class:
package BankAccount;
public class BankAccount implements Comparable<BankAccount> {
String accountNumber;
String firstName, lastName;
char middleInitial;
double balance;
public static double OVERDRAFT_FEE = 26.00;
public BankAccount(String acno, String fName, char midInit, String lName, double initBal){
acno = accountNumber;
fName = firstName;
midInit = middleInitial;
lName = lastName;
initBal = balance;
}
public String getAccountNumber(){
return accountNumber;
}
public String getFirstName(){
return firstName;
}
public char getMiddleInitial(){
return middleInitial;
}
public String getLastName(){
return lastName;
}
public double getBalance(){
return balance;
}
public void deposit(double amount){
if (amount > 0)
balance = balance + amount;
else
throw new IllegalArgumentException("deposit(double amount): Amount cannot be less than 0.");
}
public void withdraw(double amount){
if (balance >= amount && amount > 0)
balance = balance - amount;
else if(balance < amount && amount > 0)
balance = balance - amount - OVERDRAFT_FEE;
else
throw new IllegalArgumentException("withdraw(double amount): Amount cannot be less than 0.");
}
#Override
public int compareTo(BankAccount another){
if (Integer.parseInt(this.getAccountNumber()) > Integer.parseInt(another.getAccountNumber()))
return 1;
else if(Integer.parseInt(this.getAccountNumber()) < Integer.parseInt(another.getAccountNumber()))
return -1;
else
return 0;
}
}
My main method looks like this:
public class GeauxBank
{
public static void main(String[] args)
{
ArrayList<BankAccount> accounts = new ArrayList<BankAccount>();
Scanner keyb = new Scanner(System.in);
// write code to read data from acinfo.dbf. Be sure to handle
// FileNotFoundException in a try-catch statement. You don't
// need to do anything in the catch block.
int option;
String acno;
String fName;
char midInit;
String lName;
double initBal=0,amount;
int pos;
do
{
menu();
System.out.println();
System.out.print("Select an option->");
option = keyb.nextInt();
System.out.println();
switch(option)
{
case 1:
System.out.print("Enter a 10-character long account number->");
acno = keyb.next();
System.out.print("Customer's first name ->");
fName = keyb.next();
System.out.print("Customer's middle initial ->");
midInit = keyb.next().charAt(0);
System.out.print("Customer's last name ->");
lName = keyb.next();
System.out.print("Initial Deposit ->");
initBal = keyb.nextDouble();
Collections.sort(accounts);
pos = binarySearch(accounts,acno);
if (pos < 0)
{
try
{
accounts.add(new BankAccount(acno,fName,midInit,lName,initBal));
Collections.sort(accounts);
}
catch(IllegalArgumentException e)
{
System.out.println(e);
}
}
else
System.out.println(acno+" has already being asssigned another customer");
break;
case 2:
System.out.println("Enter the 10-character long account number of the account you wish to close->");
acno = keyb.next();
pos = binarySearch(accounts, acno);
accounts.remove(pos);
break;
case 3:
System.out.println("Enter the 10-character long account number->");
acno = keyb.next();
System.out.println("Enter the amount you wish to deposit->");
amount = keyb.nextDouble();
pos = binarySearch(accounts, acno);
accounts.get(pos).deposit(amount);
break;
case 4:
System.out.println("Enter the 10-character long account number->");
acno = keyb.next();
System.out.println("Enter the amount you wish to withdraw->");
amount = keyb.nextDouble();
accounts.get(binarySearch(accounts, acno)).withdraw(amount);
break;
case 5:
System.out.println("Enter the 10-character long account number->");
acno = keyb.next();
accounts.get(binarySearch(accounts, acno)).getBalance();
break;
case 6:
int i;
int length = accounts.size();
for(i = 0; i < length; i++) {
System.out.print(accounts.get(i).getFirstName()+" ");
System.out.print(accounts.get(i).getMiddleInitial()+" ");
System.out.println(accounts.get(i).getLastName());
}
break;
case 0:
break;
default:
System.out.println("Invalid menu option");
}
}while (option != 0);
try{
PrintWriter writer = new PrintWriter("acinfo.dbf");
int i;
int length = accounts.size();
for(i = 0; i < length; i++){
writer.write(accounts.get(i)+"");
}
writer.close();
}
catch(FileNotFoundException f) {
System.out.println("The file acinfo.dbf does not exist.");
}
}
/**
* displays a text-based menu interface for this application
*/
public static void menu()
{
System.out.println();
System.out.println("G E A U X B A N K L O U I S I A N A L T D.");
System.out.println("=================================================");
System.out.println("[1]...............................open an account");
System.out.println("[2]..............................close an account");
System.out.println("[3].......................................deposit");
System.out.println("[4]....................................withdrawal");
System.out.println("[5]...............................balance inquiry");
System.out.println("[6].............................customers listing");
System.out.println("[0]..........................................exit");
System.out.println("=================================================");
}
/**
* searches an array list of BankAccount objects for a matching
* account number using the Binary Search algorithm.
* #param accounts an array list of BankAccount objects
* #param acno a string
* #return the index of the BankAccount object in the array list or
* with the account number that is the same as acno if such a BankAccount
* object can be found in the accounts array list; otherwise, the negative
* of the position the BankAccount object whose account number would
* have matched acno had it been found.
*/
public static int binarySearch(ArrayList<BankAccount> accounts, String acno)
{
int i;
int low,mid=0,high;
low = 0;
high = accounts.size()-1;
while (low <= high)
{
mid = (low+high)/2;
if (acno.compareTo(accounts.get(mid).getAccountNumber())==0)
return mid;
else if (acno.compareTo(accounts.get(mid).getAccountNumber())< 0)
high = mid-1;
else
low = mid+1;
}
return -1-mid;
}
}
I'm having problems with the binarySearch method. I can create one bank account just fine but when I try to create a second one, I get this message:
Exception in thread "main" java.lang.NullPointerException
at java.lang.String.compareTo(String.java:1167)
at geauxbank.GeauxBank.binarySearch(GeauxBank.java:172)
at geauxbank.GeauxBank.main(GeauxBank.java:57)
Java Result: 1
It also gives me a similar message any time I try to use any other case in the switch statement that uses the binarySearch method. I don't know why this is. Also, when I try to write the information to a text file, I get this in the text file: BankAccount.BankAccount#1b67f74
or this: null null
I really don't know what is causing these problems. Any insight and clarity would be appreciated.
Your assignments are the wrong way around.
This takes the parameter and overwrites it with the fields which is null. The fields is left as null and you get an NPE when you attempt to dereference it.
acno = accountNumber;
try
accountNumber = acno;
I suggest you make fields final (unless you need to be able to change them) and you won't have this problem.
Related
When I run the program and and put in a couple mortgages and then end the program it prints out the entire array of objects, mortgageArray[], but for some reason it is only printing out the last mortgage you entered. Not sure why can anybody help me out? I think the problem may lie when instantiating the objects into the array.
Mortgage Class
import java.util.*;
import java.lang.Math.*;
import java.text.DecimalFormat;
public class Mortgage {
private static int loanAmount;
private static int term;
private static double interestRate;
private static String accountNum;
private static String lastName;
private static double monthlyPayment;
private static double totalPayment;
public Mortgage(int loanAmount1, int term1, double interestRate1, String accountNum1){
loanAmount = loanAmount1;
term = term1;
interestRate = interestRate1;
accountNum = accountNum1;
}
public void promotional(){
Mortgage m = new Mortgage();
m.storeLastName();
m.storeAccountNum();
lastName = getLastName();
accountNum = getAccountNum();
monthlyPayment = m.calcMonthlyPayment();
totalPayment = m.calcTotalPayment();
}
public void unique(){
Mortgage m = new Mortgage();
m.storeLastName();
m.storeAccountNum();
m.storeLoanAmount();
m.storeInterestRate();
m.storeTerm();
monthlyPayment = m.calcMonthlyPayment();
totalPayment = m.calcTotalPayment();
}
public Mortgage(){
//dummy constructor
}
public static int getLoanAmount(){
return loanAmount;
}
public void storeLoanAmount(){
Scanner s = new Scanner(System.in);
System.out.println("Enter the amount of the loan (Ex:75000): ");
int loanAmount1 = s.nextInt();
while(loanAmount1 < 75000 || loanAmount1 > 1000000){
System.out.println("\tValid Loan Amounts are $75000-$1000000");
System.out.println("\tPlease re-enter loan amount without $ or commas (Ex:75000): ");
loanAmount1 = s.nextInt();
}
loanAmount = loanAmount1;
}
public static int getTerm(){
return term;
}
public void storeTerm(){
Scanner s = new Scanner(System.in);
System.out.println("Enter number of years for the loan: ");
int term1 = s.nextInt();
while(term1 < 10 || term1 > 40){
System.out.println("\tValid Loan Terms are 10-40");
System.out.println("\tPlease re-enter valid number of years: ");
term1 = s.nextInt();
}
term = term1;
}
public static double getInterestRate(){
return interestRate;
}
public void storeInterestRate(){
Scanner s = new Scanner(System.in);
System.out.println("Enter yearly interest rate (Ex: 8.25): ");
double interestRate1 = s.nextDouble();
while(interestRate1 < 2 || interestRate1 > 7){
System.out.println("\tValid Interest Rates are 2% - 7%");
System.out.println("\tPlease re-enter valid yearly interest rate (Ex: 8.25): ");
interestRate1 = s.nextDouble();
}
interestRate = interestRate1;
}
public String getLastName(){
return lastName;
}
public void storeLastName(){
Scanner s = new Scanner(System.in);
System.out.println("Enter customer's Last Name Only: ");
String lastName1 = s.nextLine();
lastName = lastName1;
}
private double calcMonthlyPayment(){
int months = term * 12;
double monthlyInterest = (interestRate / 12 / 100);
double monthlyPay = (loanAmount * monthlyInterest) / (1 - Math.pow(1+ monthlyInterest, -1 * months));
return monthlyPay;
}
private double calcTotalPayment(){
double totalPay = calcMonthlyPayment() * term * 12;
return totalPay;
}
public String getAccountNum(){
return accountNum;
}
public void storeAccountNum(){
StringBuilder accountNum1 = new StringBuilder();
Random rand = new Random();
int accNum = rand.nextInt(9900);
accNum += 100;
accountNum1.append(lastName.substring(0,4));
accountNum1.append(accNum);
accountNum = accountNum1.toString();
}
public String toString(){
DecimalFormat df = new DecimalFormat("#,###.00");
String strMonthlyPayment = ("$" + df.format(calcMonthlyPayment()));
String strTotalPayment = ("$" + df.format(calcTotalPayment()));
return("Account Number: " + accountNum + "\nThe monthly payment is " + strMonthlyPayment + "\nThe total payment is " + strTotalPayment);
}
}
MortgageApp Class
import java.util.*;
public class MortgageApp {
public static void main(String [] args){
Scanner s = new Scanner(System.in);
Mortgage m = new Mortgage();
int size = 10;
Mortgage [] mortgageArray = new Mortgage [size];
int index = 0;
for(index = 0; index < size; index++){
int choice;
System.out.println("\nPlease choose from the following choices below:");
System.out.println("\t1) Promotional Load (preset loan amount, rate, term)");
System.out.println("\t2) Unique Loan (enter in loan values)");
System.out.println("\t3) Quit (Exit the program)");
System.out.println("\n\t Please enter your selection (1-3): ");
choice = s.nextInt();
while(choice < 1 || choice > 3){
System.out.println("\t\tInvalid Choice. Please select 1, 2, or 3: ");
choice = s.nextInt();
}
if(choice == 1){
m.promotional();
String accountNum1 = m.getAccountNum();
mortgageArray[index] = new Mortgage(250000, 20, 3.2, accountNum1);
System.out.println("PROMOTIONAL LOAN...:");
System.out.println(mortgageArray[index].toString());
}
else if(choice == 2){
m.unique();
int loanAmount = m.getLoanAmount();
int term = m.getTerm();
double interestRate = m.getInterestRate();
String accountNum1 = m.getAccountNum();
mortgageArray[index] = new Mortgage(loanAmount, term, interestRate, accountNum1);
System.out.println("UNIQUE LOAN...:");
System.out.println(mortgageArray[index].toString());
}
else if(choice == 3){
System.out.println("\nPROGRAM COMPLETE");
System.out.println("Contents of Array...");
for(int j = 0; j < 10; j++){
if(mortgageArray[j] != null){
System.out.println(mortgageArray[j].toString() + "\n");
}
}
index = 10;
}
}
}
}
The problem is with your loop at the end
for(int j = 0; j < 10; j++){
if(mortgageArray[j] != null){
System.out.println(mortgageArray[1].toString() + "\n");
}
}
It always prints the element at index 1.
Should be
System.out.println(mortgageArray[j].toString() + "\n");
All your fields in the class Mortgage are static.
To fix this, simply remove the static keyword:
private int loanAmount;
private int term;
private double interestRate;
private String accountNum;
private String lastName;
private double monthlyPayment;
private double totalPayment;
Static fields don't belong to an instance, but to the class that gets instantiated. So everytime you call one of your getter-methods, the previous value (of all your instances) will be overriden.
If you are not familiar with classes and objects in Java, this tutorial might be helpfull for you: Understanding Class Members
I had made a program that creates 10 basic accounts with an ID consisting of four digits and a default balance of 100.I am attempting to create additional accounts(checking accounts) with more restrictions/additional information.In order to access the accounts, you must enter your id which is displayed in a list of all possible id's(to avoid guessing id's).My issue is now that I have created 10 Checkingaccount objects with my initial 10 standard account objects my program will not assign a random four digit ID to both objects.object accounts gets ID's fine but if you run the program the Checkingaccount objects receive no ID's.Why?
I have tried for hours and I am very new to this so please forgive me if this is in some way broken or incorrect.I really appreciate the time you take to give me help!
import java.util.Scanner;
import java.util.Random;
public class Chapter10_7 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
CheckingAccount[] Checkingaccount = new CheckingAccount[10];//create ten CHECKING ACCOUNT objects
account[] accounts = new account[10];//create ten accounts objects
for (int i = 0; i < accounts.length; i++) {
Random r = new Random();
int ID = +((int)(Math.random()*9000)+1000);//ID is 4 digit number
accounts[i] = new account(ID, 100); //assign random 4 digit ID to accounts[1-10]
System.out.println(ID);
}
System.out.println("\n--Checking Accounts--\n");
for (int i = 0; i < Checkingaccount.length; i++) {
Random r = new Random();
int ID = +((int)(Math.random()*9000)+1000);//ID is 4 digit number
Checkingaccount[i] = new CheckingAccount(ID, 100); //assign random 4 digit ID to CHECKING ACCOUNT[1-10]
System.out.println(ID);
}
boolean hasRan = false;
int q = 0;
int a = q;
int userID = 0;
int accountID = 0;
int CheckingaccountID = 0;
int z = 0;
while(z != 4){//run until user enters 4
while(hasRan == false){//runs once and never again unless its incorrect ID
System.out.println("Enter Account ID");
userID = input.nextInt();
for(a = 0; a < accounts.length; a++){
accountID = accounts[a].getId(); //accountID gets accounts[a] ID variable and stores it(4 digit ID).getId
CheckingaccountID = Checkingaccount[a].getId();
if(userID == accountID){//if your input of ID equals an accounts pin(any of them) it allows access
System.out.println("Welcome");
hasRan = true;//stops it from looping
break;
}if(userID == CheckingaccountID){//if your input of ID equals a Checking Account pin(any of them) it allows access
System.out.println("Welcome");
hasRan = true;//stops it from looping
break;
}else if(userID != accountID){
hasRan = true;//loop if you entered incorrect pin
}
}
}
if(userID == accountID){// if ID matches an existing accounts ID then access
System.out.println("\n1:Check Balance\n2:Deposit\n3:Withdraw\n4:Exit");
int x = input.nextInt();
//accounts[a] is the account array,1-10 since we have 10 accounts.
if (x == 1){
System.out.println("Your Balance Is: " + accounts[a].getBalance());
accounts[a].getBalance();
}else if (x == 2){
System.out.println("How Much Would You Like To Deposit?");
int newDeposit = input.nextInt();
accounts[a].deposit(newDeposit);
System.out.println("Your Total Is: "+ accounts[a].getBalance());
}else if(x == 3){
System.out.println("How Much Would You Like To Withdraw?");
int newWithdraw = input.nextInt();
accounts[a].withdraw(newWithdraw);
System.out.println("Your Total Is: "+ accounts[a].getBalance());
}else break;
}else{
hasRan = false;// allows ID check to run again
}
}
}
}
-This is the class I created to use only 10 basic "accounts" objects.
class account{
private int id = 0;
private double balance = 100;
public account(int newId , double newBalance ){
id = newId;
balance = newBalance;
}
public double getBalance() {
return balance;
}
public void setBalance(double newBalance) {
balance = newBalance;
}
public int getId() {
return id;
}
public void setId(int newId) {
id = newId;
}
public double deposit(double newDeposit){
balance = balance + newDeposit;
return newDeposit;
}
public double withdraw(double newWithdraw){
balance = balance - newWithdraw;
return newWithdraw;
}
#Override
public String toString() {
return "\r\n"+"Account ID: " + id + "\r\n" + "Balance: " + balance + "\r\n" ;
}
}
-I tried to make Checking Accounts work in a seperate class from accounts
import java.util.Random;
public class CheckingAccount {
private double balance;
private int id;
public CheckingAccount(int newId , double newBalance){
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public int getId() {
return id;
}
public void setID(int newId){
id = newId;
}
}
Your Question accounts gets ID's fine but if you run the program the Checkingaccount objects receive no ID's.Why?
You create the object like
new CheckingAccount(ID, 100);
but your constructor is wrong and is not saving the passed values
You should change it to
public CheckingAccount(int newId , double newBalance){
this.id = newId;
balance = newBalance;
}
Also,why are you instantiating
Random r = new Random();
when you never use it.
New Class
public class NewClass {
private String accountNumber;
private String accountName;
private double balance;
public NewClass(String nameIn, String numberIn) {
accountNumber = numberIn;
accountName = nameIn;
balance = 0;
}
public String getAccountName() {
return accountName;
}
public String getAccountNumber() {
return accountNumber;
}
public double getBalance() {
return balance;
}
public void deposit(double amountIn) {
balance = balance + amountIn;
}
public boolean withdraw(double amountIn) {
if (amountIn < 0 && balance < 0) {
return false;
} else {
balance = balance - amountIn;
return true;
}
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
}
Main Class
public static void main(String[] args) {
String accountName = "";
String accountNum = "";
Scanner sc = new Scanner(System.in);
boolean IsAccount = false;
NewClass[] accountList = new NewClass[3];
accountList[0] = new NewClass(accountName, accountNum);
accountList[1] = new NewClass(accountName, accountNum);
accountList[2] = new NewClass(accountName, accountNum);
int i = 0;
int count = 3;
while (i < count) {
double amount;
System.out.print("Enter the account name: ");
accountName = sc.next();
accountList[i].setAccountName(accountName);
System.out.println("Enter the account number: ");
accountNum = sc.next();
accountList[i].setAccountNumber(accountNum);
System.out.print("Enter amount to deposit: ");
amount = sc.nextDouble();
accountList[i].deposit(amount);
System.out.print("Enter amount to withdraw: ");
amount = sc.nextDouble();
accountList[i].withdraw(amount);
i++;
}
while (i < count) {
System.out.println(accountList[i].getAccountNumber());
System.out.println(accountList[i].getAccountName());
System.out.println(accountList[i].getBalance());
}
}
I am new to java programming and am having trouble with my bank account program. The output is to show three accounts each containing a name, account number and balance. This i cant get to show. Any help would be greatly appreciated. Thank You.
It looks like you don't reset i back to 0 before the loop that's supposed to print the output, which means that i==count due to the previous loop, so the loop that prints the output is never entered.
Here's what you have to fix:
int i = 0; // add this
while (i < count){
System.out.println(accountList[i].getAccountNumber());
System.out.println(accountList[i].getAccountName());
System.out.println(accountList[i].getBalance());
i++; // add this too
}
Of course you can make your code more elegant with the enhanced for loop :
for (NewClass account : accountList) {
System.out.println(account.getAccountNumber());
System.out.println(account.getAccountName());
System.out.println(account.getBalance());
}
I am working on a simple program for my intro to Object Oriented programing class, where I have 3 classes: Account, ATM and the main/Runner class.
I am experiencing a null pointer exception error in the constructor of the ATM class when I am trying to initialize the array of Accounts using a loop. I am new to Java so I don't really know what happens.
Here is the code:
import java.util.Date;
public class Account {
private int account_id;
private double account_balance;
private static double annual_interest_rate;
private Date date_Created;
Account(){
account_id = 0;
account_balance=0;
annual_interest_rate = 0;
date_Created = new Date();
}
Account(int account_id_in,
double account_balance_in, double annual_interest_rate_in) {
account_id = account_id_in;
account_balance = account_balance_in;
annual_interest_rate = annual_interest_rate_in;
date_Created = new Date();
}
int get_account_id(){
return account_id;
}
double get_account_balance(){
return account_balance;
}
double get_annual_interest_rate(){
return annual_interest_rate;
}
Date get_date_created(){
return date_Created;
}
void set_account_id(int account_id_in){
account_id = account_id_in;
}
void set_account_balance(double account_balance_in){
account_balance = account_balance_in;
}
void set_annual_interest_rate(double annual_interest_rate_in){
annual_interest_rate = annual_interest_rate_in;
}
double get_monthly_interest_rate(){
return annual_interest_rate/12;
}
double get_monthly_interest(){
return (account_balance * get_monthly_interest_rate())/100;
}
void perform_deposit(double deposit_in){
account_balance += deposit_in;
}
void perform_withdraw(double withdraw_amount){
account_balance -= withdraw_amount;
}
}
public class ATM {
private Account[] acct = new Account [10];
public ATM(){
//acct = new Account[10];
for(int i = 0; i<10 ; i++){
acct[i].set_account_id(i+1);
acct[i].set_account_balance(100); // here iam getting an error.
}
//you must set their ids to values as specified in the assignment
} //these are the teacher's comments and instructions.
public void displayMenu(){
System.out.println("ATM Menu:");
System.out.println("\tenter 1 for viewing the current balance");
System.out.println("\tenter 2 for withdrawing money");
System.out.println("\tenter 3 for for depositing money");
System.out.println("\tenter 4 for exiting the main menu");
}
public boolean checkID(int id){
for(int i = 0; i<10 ; i++){
if(acct[i].get_account_id() == id){
return true;
}
}
return false;
}
public double checkBalance(int idToSearch){
int indexOfAccountToReturn = 0;
for(int i = 0; i<10; i++){
if(acct[i].get_account_id() == idToSearch){
indexOfAccountToReturn = i;
break;
}
}
return acct[indexOfAccountToReturn].get_account_balance();
}
public void withdrawFunds(int id, double amount){
for(int i=0; i<10; i++){
if(acct[i].get_account_id() == id){
acct[i].perform_withdraw(amount);
break;
}
}
}
public void depositFunds(int id, double amount){
for(int i=0; i<10; i++){
if(acct[i].get_account_id() == id){
acct[i].perform_deposit(amount);
break;
}
}
}
}
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Banking_Finance_Main {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ATM atm = new ATM();
Scanner input = new Scanner(System.in);
do{
System.out.println("Account ID?");
int id = input.nextInt();
while(!(atm.checkID(id))){
String entry =
JOptionPane.showInputDialog("Incorrect Input");
id = Integer.parseInt(entry);
}
//prevent user to proceed without the correct id; use checkID method and store appropriately
do{
atm.displayMenu();
System.out.println("Your choice?");
int choice = input.nextInt();
while((choice >4) || (choice <1)){
String entry = JOptionPane.showInputDialog("Incorrect Imput");
choice = Integer.parseInt(entry);
}
//prevent user to proceed without the correct choice 1-4;
if(choice==1){
System.out.println("Enter the Account id to check the balance: ");
int idToSearch = input.nextInt();
System.out.println("The balance in this ACccount is: $" + atm.checkBalance(idToSearch));
}else if(choice==2){
System.out.println("Enter the Account id to perform withdrawal: ");
int idToSearch = input.nextInt();
System.out.println("Enter the amount to be withdrawn: ");
double amountToWithdraw = input.nextDouble();
atm.withdrawFunds(idToSearch, amountToWithdraw);
}else if(choice==3){
System.out.println("Enter the Account id to perform deposit: ");
int idToSearch = input.nextInt();
System.out.println("Enter the amount to be deposited: ");
double amountToDeposit = input.nextDouble();
atm.depositFunds(idToSearch, amountToDeposit);
}else{
break;
}
}while(true);
}while(true);
}
}
I am sorry if I am using this site inappropriately, this is my first question here so bear with me please.
I managed to pass through the error with the following fix:
public ATM(){
for(int i = 0; i<10 ; i++){
acct[i] = new Account();
acct[i].set_account_id(i+1);
acct[i].set_account_balance(100);
}
//you must set their id's to values as specified in the assignment
}
However I am not sure if this is correct or not. Is it?
The problem here is that this line:
private Account[] acct = new Account [10];
only initializes space for 10 Account instances, it doesn't actually construct 10 account instances and put them in the array.
In the for loop in your ATM constructor, you need to first call acct[i] = new Account();
Beside creating array you also need to fill it with objects. Update your code in ATM constructor:
for (int i = 0; i < 10; i++) {
acct[i] = new Account(); // add this line to crate account
// and place it in array
acct[i].set_account_id(i + 1); // also you are getting error here
acct[i].set_account_balance(100); // not here because you ware trying to
// invoke method on `null`
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
So I am still fairly new to java. I have written this but am not sure as to why when I run it, the amounts will not add to what is set in the client.
For example: I enter 500 as starting balance, if I hit deposit, and type 500, and then hit case 3, it should say 1000 but it still says 500. And then If i hit withdraw, it says I have -500.
Any ideas? Thanks
package bankaccount;
import java.util.Random;
import java.util.Scanner;
public class Client {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your Name: ");
String cusName = input.nextLine();
Random randomGenerator = new Random();
int accNo = randomGenerator.nextInt(100000);
System.out.println("Enter Initial Balance: ");
int balance = input.nextInt();
BankAccount b1 = new BankAccount(cusName, accNo, balance);
int menu;
System.out.println("Menu");
System.out.println("1. Deposit Amount");
System.out.println("2. Withdraw Amount");
System.out.println("3. Display Information");
System.out.println("4. Exit");
boolean quit = false;
do {
System.out.print("Please enter your choice: ");
menu = input.nextInt();
switch (menu) {
case 1:
System.out.print("Enter depost amount:");
Money.amount = input.nextInt();
b1.getDeposit();
break;
case 2:
System.out.println("Current Account Balance=" + b1.getBalance());
System.out.print("Enter withdrawal amount:");
Money.amount = input.nextInt();
b1.getWithdraw();
break;
case 3:
b1.display();
break;
case 4:
quit = true;
break;
}
} while (!quit);
}
public class Money
{
public static int accountNumber, balance=0;
static int amount;
static String name;
public void setDeposit(int amount) {
balance = balance + amount;
}
public int getDeposit()
{
balance = balance + amount;
if (amount < 0) {
System.out.println("Invalid");
}
return 1;
}
public void setBalance(int b)
{
b = balance;
}
public int getBalance()
{
return balance;
}
public void setWithdraw(int amount) {
balance = balance - amount;
}
public int getWithdraw()
{
balance = balance - amount;
if (balance < amount)
{
System.out.println("Not enough funds.");
return 1;
}
else if (amount < 0) {
System.out.println("Invalid");
return 1;}
else
return 0;
}
import java.util.*;
public class BankAccount extends Money {
static String name;
public static int balance, amount, acctNum;
Money customerMoney;
BankAccount(String name, int accNo, int bal) {
this.name = name;
this.acctNum = accNo;
this.balance = bal;
this.customerMoney = new Money();
}
void display() {
System.out.println("Name:" + name);
System.out.println("Account No:" + acctNum);
System.out.println("Balance:" + balance);
}
void displayBalance() {
System.out.println("Balance:" + balance);
}
public Money getMoney(){
return this.customerMoney;
}
}
The biggest problem is at statement balance=0
public static int accountNumber, balance=0;
^^^^^^^^^
Every time when you are going to insert amount, your balance is ZERO.
You should have used setDeposit(input.nextInt())
In public void setBalance(int b), b = balance; should have been balance = b;
Also, your amount, balance variables should be Float instead of int as balance/amount can be 23434.22.
I would remove all the public static int variables that you are using. These are going to cause confusion because it's much harder to follow what their values are as the program executes. Best to encapsulate your logic into BankAccount using private variables and public methods to modify them.
I would, personally, eliminate the Money class from your code. It's just going to cause confusion and with your simplified logic is not required. Let's assume the account holds some arbitrary count of 'money' but there is no real-life money actually backing it up - (kind of like real life, it's just 'numbers on a screen' right?) - in this case we wouldn't need the Money class, just an int for our BankAccount's balance.
Without trying to make too many changes to your underlying functionality, I rewrote as the below two classes:
A BankAccount class:
package banking;
public class BankAccount {
/**
* The balance of this account. <br/>
* Assumes integer money (Floating point math is horrible and who really
* needs pesky pence or cents right?!)
*/
private int balance;
/**
* The account number
*/
private final int acctNum;
/**
* Name of the account holder
*/
private final String name;
/**
* Construct our basic account with an account number, account holder and
* starting balance.
*
* #param name
* #param accNo
* #param bal
*/
public BankAccount(String name, int accNo, int bal) {
this.name = name;
this.acctNum = accNo;
this.balance = bal;
}
/**
* Make a deposit to this account by adding a fixed sum to the existing
* balance. <br/>
*
* #param amount
*/
public void deposit(int amount) {
if (amount <= 0) {
throw new IllegalArgumentException("You cannot deposit zero or less");
} else {
this.balance += amount;
}
}
/**
* Make a withdrawal from this account by subtracting a fixed amount from
* the existing balance. <br/>
*
* #param amount
*/
public void withdraw(int amount) {
if (amount > balance) {
throw new IllegalArgumentException("Insufficient Funds");
} else if (amount <= 0) {
throw new IllegalArgumentException("You cannot withdraw zero or less");
} else {
balance -= amount;
}
}
/**
* Get the account holder name.
*
* #return
*/
public String getName() {
return name;
}
/**
* Get the current account balance.
*
* #return
*/
public int getBalance() {
return balance;
}
/**
* Get the account identifier for this account.
*
* #return
*/
public int getAcctNum() {
return acctNum;
}
/**
* Debug print method.
*/
public void display() {
System.out.println("Name:" + name);
System.out.println("Account No:" + acctNum);
System.out.println("Balance:" + balance);
}
}
And the main class:
package banking;
import java.util.Random;
import java.util.Scanner;
public class BankMain {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your Name: ");
String customerName = input.nextLine();
Random randomGenerator = new Random();
int acctNo = randomGenerator.nextInt(100000);
System.out.println("Enter Initial Balance: ");
int balance = input.nextInt();
BankAccount acct = new BankAccount(customerName, acctNo, balance);
System.out.println("Menu");
System.out.println("1. Deposit Amount");
System.out.println("2. Withdraw Amount");
System.out.println("3. Display Information");
System.out.println("4. Exit");
boolean quit = false;
int menu;
do {
final int transaction;
System.out.print("Please enter your choice: ");
menu = input.nextInt();
switch (menu) {
case 1:
System.out.print("Enter depost amount:");
transaction = input.nextInt();
acct.deposit(transaction);
break;
case 2:
System.out.println("Current Account Balance=" + acct.getBalance());
System.out.print("Enter withdrawal amount:");
transaction = input.nextInt();
try {
acct.withdraw(transaction);
} catch (IllegalArgumentException iaEx) {
System.out.println(iaEx.getMessage());
}
break;
case 3:
acct.display();
break;
case 4:
quit = true;
break;
}
} while (!quit);
}
}
This is still far from perfect, but I feel it's easier to follow for having the static variables and Money class removed.
You have many problems with the code e.g. none of your fields should be static, but the main one is that you have multiple duplicated fields.
e.g. In Money you have
public static int accountNumber, balance=0;
static int amount;
static String name;
and in BankAccount you have
static String name;
public static int balance, amount, acctNum;
Money customerMoney;
which means you have multiple fields called name, balance and amount. Some of the code uses the first group of fields and some of the code uses the second. You also have a customerMoney which is not updated directly.
To avoid confusion I suggest you have each field be non-static and in only one place. Remove the customerMoney as you might be tempted to use it ;)