Dylan Broussard
Dylan Broussard

Reputation: 75

binarySearch errors in Java

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.

Upvotes: 1

Views: 435

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533530

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.

Upvotes: 2

Related Questions