-2

I keep receiving this error but I cannot see any logical errors in my code.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

private double getValueOrDefault(String symbol, double defaultValue) {
    double value = getValue(symbol);

    if (value != -1)
        return value;
    else
        return defaultValue;
}

public void createStocks() {
    // try get stock realtime values
    stocks.add(new TechStock("BB", 30.3));
    stocks.add(new TechStock("GOOG", getValueOrDefault("GOOG", 5.8)));
    stocks.add(new TechStock("AMZN", getValueOrDefault("AMZN", 6.3)));
    stocks.add(new FinanceStock("GLNG", getValueOrDefault("GLNG", 121)));
}

public static double getValue(String symbol) {
    // read data
    try {
        URL url = new URL(API_URL.replace("XXX", symbol));
        Scanner s = new Scanner(url.openStream());

        // find price
        while (s.hasNextLine()) {
           String line = s.nextLine();

           if (line.startsWith("\"price\"")) {
               // split shenanigans
               String[] f = line.split("\"");
               return Double.parseDouble(f[3]);
           }
        }

       // if we reached here: the stock is invalid
       return -1;
    } catch (Exception ex) {
       ex.printStackTrace();
    }
    return -1;
}


public class StockFrame extends Frame 
{
    private int amount;
    private Portfolio portfolio;
    private ArrayList <StockMarket> stocks = new ArrayList<StockMarket>();   
    private TextArea stockDetails;
    private TextField purchaseCode;
    private boolean found = false;

private int locateStock() {
    for(int i = 0; i<stocks.size(); i++) {
        if(stocks.get(i).getCode().equals(purchaseCode.getText())) { 
            return i;
        }
   }
   return -1;
}

private void a() {

int position = locateStock();
if(position != -1){
    StockMarket bs = stocks.get(position);
.....
}

I tried changing I to 1 but I still receive the NullPointerException. The error seems to be located at the int position = locateStock(); but I am unsure.

  • 5
    Do you think you're giving enough information? – Yassin Hajaj Mar 24 '16 at 21:34
  • 7
    See this link: http://stackoverflow.com/q/218384/3973077 – Paul Boddington Mar 24 '16 at 21:34
  • You for future references, it is always best to show the whole stack and point out to which line of code that goes. With your error description we do not know where exactly it happens. It is especially hard, because you did not paste the whole code and we are only guessing where that NullPointerException could be. – Jernej K Mar 24 '16 at 21:36
  • I suggest you read the stack trace to see which line is the cause, then add a breakpoint on this line and run your program in the debugger in your IDE. Then you will be able to see which value is `null`. – Peter Lawrey Mar 24 '16 at 21:36
  • @PeterLawrey The lines which coem up for the stack trace errors are the if(stocks.get(i).getCode().equals(purchaseCode.getText())) and the int position = locateStock(); – A Sehailia Mar 24 '16 at 21:38
  • Can you post the stacktrace and the complete code of the classes? – David Fernandez Mar 24 '16 at 21:38
  • @DavidFernandez its quite abit but i will do it below – A Sehailia Mar 24 '16 at 21:40
  • Seems like stocks, stock and ourchaseCode could be `null` :) I would use the debugger and maybe declare variables for each instance the methods returns (`stock = stocks.get(i)`, etc). Then you can check each of them and see which one is the one with `null` as a value. – Jernej K Mar 24 '16 at 21:40
  • @ASehailia so one of the expressions in that line is `null`. I suggest you use your debugger to see which one it is. – Peter Lawrey Mar 24 '16 at 21:42

1 Answers1

-1

A NullPointerException occurs when you try to reference an object that hasn't been declared at that point in the execution of your program.

The fact that you still got the exception when you tried changing the initial value of i to 1 tells me that when you call locateStock(), your List of TechStocks hasn't been initialized with a new List<TechStock>() statement prior to calling locateStock(). Therefore, when you try to declare the for loop using stocks.size(), you get an exception, since stocks is null at that point.

However, it's difficult to say how to exactly fix your problem because you didn't really offer enough information in your snippet for anyone to know how that code fits in context with the rest of your program.

NAMS
  • 983
  • 7
  • 17
  • TechStock and all other sub-types are all subclasses which all go into the same arrayList stocks. – A Sehailia Mar 24 '16 at 21:48
  • It's not the TechStock that's the issue, its the ArrayList stocks itself. If you haven't instantiated it before you try to call size() or get() on it, you will get an Exception. Since in one of the comments above you pointed out this line as the location of the error: `if(stocks.get(i).getCode().equals(purchaseCode.getText()))`, this means that: a) `stocks.get(i)` will throw an exception if stocks is null, which I suspect is the case, since at no point in your code do I see a new ArrayList(). b) `stocks.get(i).getCode()` will throw an exception if the TechStock object at index i is null. – NAMS Mar 24 '16 at 22:00
  • Stocks is initialised here: private ArrayList stocks = new ArrayList();. Can you please expand on the point b since i get the feeling that the error is occuring there. – A Sehailia Mar 24 '16 at 22:19