-4

The code is to simiulate selling stock using FIFO and LIFO. I am only trying to get FIFO to work right now, we are using the Strategy Pattern. Me and my friend believe the code we have is correct, as there are no errors untilyou run the code. Below I have all my classes (labeled 1-5, as well as the output(labeled Output))

Class 1

package cop4814;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

public class Portfolio {
private SellStrategy strategy;
List<Transaction> buyList = new ArrayList<>();
List<Transaction> sellList = new ArrayList<>();

public boolean readDataFile(String path) {
    try {
        Scanner in = new Scanner(new File(path));
        while (in.hasNextLine()) {
            String[] fields = in.nextLine().split(",");
            if (fields[0].equals("B")) {
                buyList.add(new Transaction(fields));
            } else if (fields[0].equals("S")) {
                sellList.add(new Transaction(fields));
            }

        }
    } catch (FileNotFoundException ex) {
        System.out.println("Error: " + ex.toString());
        return false;
    }
    return true;
}

public void processTransactions() {
    for (Transaction t : sellList) {
        System.out.println(strategy.sell(t,buyList));
    }
}

public void setSellStrategy(SellStrategy howToSell) {
    strategy = howToSell;
}

}

Class 2

package cop4814;

import java.util.List;

public interface SellStrategy 
{
   public String sell(Transaction stockToSell, List<Transaction> buyList);

}

Class 3

package cop4814;

import java.util.List;

public class Sell_FIFO implements SellStrategy {

public String sell(Transaction stockToSell, List<Transaction> buyList) {
    //Find first occurrence of stockToSell
    Transaction found = buyList.get(buyList.indexOf(stockToSell));
    //Find difference between stockToSell and the first occurrence's shares
    int diff = stockToSell.numShares - found.numShares;

    //Loop to continue finding and remove stocks or shares as needed when the difference is greater than 0
    while (diff > 0){
            //remove from buy list
            buyList.remove(stockToSell);
            //find next stock to sell and find new diff
            found = buyList.get(buyList.indexOf(stockToSell));
            diff = stockToSell.numShares - found.numShares;

    }

    //Loop has stopped because diff is now 0 or LT 0
    if (diff == 0) {
        //remove stock
        buyList.remove(stockToSell);
    } else {
        found.numShares = found.numShares - diff;
    }

    return "";
}

}

Class 4 (has my variables)

    package cop4814;

    public class Transaction {
    String action; // s or s
    String ticker;
    String datepurchased;
    int numShares;
    double purchPrice;

    public Transaction(String[] fields) {
        action = fields[0];
        datepurchased = fields[1];
        numShares = Integer.parseInt(fields[2]);
        purchPrice = Double.parseDouble(fields[3]);
        ticker = fields[4];

    }

    public boolean equals(Transaction o) {
        return this.ticker.equals(o.ticker);
    }

    }

Class 5 (My test class)

import cop4814.*;

public class PortfolioTester {

    private static final String inputFilePath = "transactions.txt";

    void start() {
        Portfolio p = new Portfolio();
        if( p.readDataFile( inputFilePath )) {
            p.setSellStrategy( new Sell_LIFO() );
            p.processTransactions();      // also prints the report
            p.setSellStrategy( new Sell_FIFO() );
            p.processTransactions();      // prints a second report
        }
        else {
            System.out.println("Unable to open input file: " + inputFilePath );
        }           
    }

    public static void main(String[] args) {
        new PortfolioTester().start();
    }

}

Output

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
    at java.util.ArrayList.elementData(ArrayList.java:418)
    at java.util.ArrayList.get(ArrayList.java:431)
    at cop4814.Sell_FIFO.sell(Sell_FIFO.java:18)
    at cop4814.Portfolio.processTransactions(Portfolio.java:43)
    at PortfolioTester.start(PortfolioTester.java:13)
    at PortfolioTester.main(PortfolioTester.java:21)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
  • 6
    "Code Will Not Compile" is not true if you are able to run it and get exception. Also take a look at http://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it – Pshemo Apr 03 '16 at 19:40
  • 4
    `ArrayIndexOutOfBoundsException` is a runtime error. This means your code compiled successfully. – blacktide Apr 03 '16 at 19:41
  • 2
    Time to learn how to use your IDE's debugger. – OldProgrammer Apr 03 '16 at 19:43

1 Answers1

0

You're receiving an ArrayIndexOutOfBoundsException, meaning you've tried to access an array with an illegal index.

The error is likely from this line:

Transaction found = buyList.get(buyList.indexOf(stockToSell));

You should check that the item exists in the list first:

if (buyList.contains(stockToSell)) {
    // do work
}
blacktide
  • 7,668
  • 6
  • 25
  • 45