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.
Related
I'm working on CS homework and have run into a problem. The end of the homework asks about using a copy constructor. The goal is to "make one Payroll object, instantiate it, make a second one, then print them both. Then, change values in the second Payroll object, and show that the changed values only appear in one and not both (that is, print out the original and the copy with slightly changed values)." I tried changing the values in the second Payroll object, but it also changes it in the first. I've listed my code below:
import java.util.Random;
public class Payroll {
private int[] employeeId;
private int[] hours;
private double[] payRate;
public Payroll(){
this.employeeId = new int[0];
this.hours = new int[0];
this.payRate = new double[0];
}
public Payroll(Payroll obj){
this.employeeId = obj.employeeId;
this.hours = obj.hours;
this.payRate = obj.payRate;
}
public Payroll(int i){
this.employeeId = new int[i];
this.hours = new int[i];
this.payRate = new double[i];
}
public int getEmployeeIdAt(int index){
return employeeId[index];
}
public int getHoursAt(int index){
return hours[index];
}
public double getPayRateAt(int index){
return payRate[index];
}
public double getGrossPay(int index){
double grossPay = hours[index] * payRate[index];
grossPay = Math.round(grossPay * 100);
return grossPay/100;
}
public void setEmployeeIdAt(int index, int id){
this.employeeId[index] = id;
}
public void setHoursAt(int index, int hrs){
this.hours[index] = hrs;
}
public void setPayRateAt(int index, double pr){
this.payRate[index] = pr;
}
public void setHoursAt(int i){
Random rand = new Random();
int randHours = rand.nextInt((50 - 15) + 1) + 15;
this.hours[i] = randHours;
}
}
import java.util.Scanner;
public class PayrollDriver {
public static void main(String[] args) {
Payroll pr = new Payroll(5);
Scanner scan = new Scanner(System.in);
int empID = 1001;
for(int i = 0; i < 5; i++){
pr.setEmployeeIdAt(i, empID);
empID++;
}
for(int i = 0; i < 5; i++){
System.out.println("Enter the hourly pay rate for employee number " + pr.getEmployeeIdAt(i) + ": ");
double payRate = scan.nextDouble();
if(payRate < 7.50){
do{
System.out.println("ERROR: Enter 7.50 or greater for pay rate: ");
payRate = scan.nextDouble();
} while(payRate < 7.50);
}
pr.setPayRateAt(i, payRate);
pr.setHoursAt(i);
}
System.out.println("PAYROLL DATA");
System.out.println("======================");
for(int i = 0; i < 5; i++){
System.out.println("Employee ID: " + pr.getEmployeeIdAt(i) + " Hours: " + pr.getHoursAt(i) + " Rate: " + pr.getPayRateAt(i) +
" Gross Pay: $" + pr.getGrossPay(i));
}
System.out.println("Would you like to run the Copy Constructor Test? Enter 'y' (lowercase) if yes, enter any other letter if no: ");
char copyTestVerify = scan.next().charAt(0);
if(copyTestVerify == 'y'){
CopyConstructorTest ct = new CopyConstructorTest();
ct.CopyTest();
}
scan.close();
}
}
The following is my CopyConstructorTest class, the one that tests whether or not the copy constructor will change the original object's values:
public class CopyConstructorTest {
public void CopyTest(){
Payroll pay = new Payroll(5);
pay.setEmployeeIdAt(0, 1001);
Payroll payCopy = new Payroll(pay);
System.out.println("Original: " + pay.getEmployeeIdAt(0));
System.out.println("Copy: " + payCopy.getEmployeeIdAt(0));
payCopy.setEmployeeIdAt(0, 5000);
System.out.println("Original after changes: " + pay.getEmployeeIdAt(0));
System.out.println("Copy after changes: " + payCopy.getEmployeeIdAt(0));
}
}
I'm not positive on what I'm doing wrong. Any help or guidance is much appreciated.
You are just copying the references to the arrays, not the actual data. Therefore whenever you change the data in one of your objects, the changes are seen in both, since they point to the same array.
The easiest way to copy the data is probably using System.arraycopy():
public Payroll(Payroll obj) {
this.employeeId = new int[obj.employeeId.length];
System.arraycopy(obj.employeeId, 0, this.employeeId, 0, obj.employeeId.length);
...
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'm new to java and have a question about default and non default constructors. My professor wants us to use the default constructor for creation of object BOOK1, and then use the non default constructor for BOOK2, BOOK3 and BOOK4. I know a constructor is used with the creation of an object, but I guess I don't understand how i'm supposed to differentiate between the two. My class code is as follows, where I have both a default and non default constructor:
import java.text.DecimalFormat;
public final class BOOKItem {
DecimalFormat intFormat = new DecimalFormat("000");
DecimalFormat doubleFormat = new DecimalFormat("$#,##0.00");
private int bookID;
private int numberInStock;
private double price;
private double totalValueOfStock;
private int code;
private String genre = "";
public BOOKItem() {
bookID = 0;
numberInStock = 0;
price = 0;
code = 0;
}
public BOOKItem(int newID, int newStock, double newPrice, int newCode) {
setID(newID);
setStock(newStock);
setCode(newCode);
setPrice(newPrice);
}
public void setStock (int newStock) {
if (newStock >= 1 && newStock <=5000) {
numberInStock = newStock;
}
else {
numberInStock = 0;
}
}
public void setCode (int newCode) {
if (newCode > 0) {
code = newCode;
}
}
public void setID (int newID) {
if (newID >=11 && newID <= 111111) {
bookID = newID;
}
else {
bookID = 0;
}
}
public void setPrice (double newPrice) {
if (newPrice >= 1.0 && newPrice <=150.0) {
price = newPrice;
}
else {
price = 0;
}
}
public int getID () {
return bookID;
}
public int getNumberInStock () {
return numberInStock;
}
public int getCode () {
return code;
}
public double getPrice () {
return price;
}
public double calcTotalValue () {
totalValueOfStock = numberInStock * price;
return totalValueOfStock;
}
public double getTotalValue () {
return totalValueOfStock;
}
public void display() {
switch (code)
{
case 1:
genre = "Romance";
break;
case 2:
genre = "Adventure";
break;
case 3:
genre = "Sci-Fi";
break;
case 4:
genre = "Mystery";
break;
}
System.out.println("Display:");
System.out.println("Book ID: " + bookID + " NumInStock: " + numberInStock + " Code: " + genre + " Price: " +
price + " TotalStockValue: " + calcTotalValue());
}
}
Here is my application that uses the constructors(sorry about the break in the class code, i dunno why its doing that):
import java.util.Scanner;
public class Project7 {
public static void main(String[] args) {
int bookID;
int numberInStock;
double price;
int code;
Scanner keyboard = new Scanner(System.in);
BOOKItem BOOK1, BOOK2, BOOK3, BOOK4;
BOOK1 = new BOOKItem();
BOOK2 = new BOOKItem();
BOOK3 = new BOOKItem();
BOOK4 = new BOOKItem();
System.out.println("Enter in a blank separated list: ID, number in stock, quality, price" +
"- use a BAD ID(<11 or >111111)");
bookID = keyboard.nextInt();
numberInStock = keyboard.nextInt();
code = keyboard.nextInt();
price = keyboard.nextDouble();
BOOK1.setID(bookID);
BOOK1.setStock(numberInStock);
BOOK1.setCode(code);
BOOK1.setPrice(price);
BOOK1.display();
System.out.println("Enter in a blank separated list: ID, number in stock, quality, price" +
"- use a BAD STOCK(>5000)");
bookID = keyboard.nextInt();
numberInStock = keyboard.nextInt();
code = keyboard.nextInt();
price = keyboard.nextDouble();
BOOK2.setID(bookID);
BOOK2.setStock(numberInStock);
BOOK2.setCode(code);
BOOK2.setPrice(price);
BOOK2.display();
System.out.println("Enter in a blank separated list: ID, number in stock, quality, price" +
"- use a BAD PRICE(>150.0)");
bookID = keyboard.nextInt();
numberInStock = keyboard.nextInt();
code = keyboard.nextInt();
price = keyboard.nextDouble();
BOOK3.setID(bookID);
BOOK3.setStock(numberInStock);
BOOK3.setCode(code);
BOOK3.setPrice(price);
BOOK3.display();
System.out.println("Enter in a blank separated list: ID, number in stock, quality, price" +
"- use ALL GOOD DATA");
bookID = keyboard.nextInt();
numberInStock = keyboard.nextInt();
code = keyboard.nextInt();
price = keyboard.nextDouble();
BOOK4.setID(bookID);
BOOK4.setStock(numberInStock);
BOOK4.setCode(code);
BOOK4.setPrice(price);
BOOK4.display();
}
}
Am I doing something incorrect with the creation of my objects? How do I use the non default constructor for BOOK2, BOOK3 and BOOK4? I created it, but perhaps i'm using it incorrectly. Any feedback would be greatly appreciated.
When you use
BOOK1 = new BOOKItem();
You are calling the default constructor (Construction without having any arguments)
After taking user input you would call the Non Default Constructor
bookID = keyboard.nextInt();
numberInStock = keyboard.nextInt();
code = keyboard.nextInt();
price = keyboard.nextDouble();
BOOK2 = new BOOKItem(bookID, numberInStock, price, code);
Use the above code to use the Parameterized Constructor (Non Default constructor)
This is called constructor overloading.
So for the objects you want to assign default values you call the default constructor
For the object you have information available with variables you sent them in the constructor that you have defined with parameters, To assign that value
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`
}
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.