CaptChilko
CaptChilko

Reputation: 3

NullPointerException in Processing, can't find the error

So I am making a simple little program and the IDE is throwing out NullPointerException (http://puu.sh/5TJLZ.png) at this line: total[0] = calc(coins[0],coins[1],coins[2]); Note that void setupCoins() and String calc() are in separate tabs and not part of the tab.

int[] coins;
String[] total;

void setup(){
  size(100,100);
  setupCoins();
  total[0] = calc(coins[0],coins[1],coins[2]);
  saveStrings("data/balance.txt",total);
}

void setupCoins(){

  String[] imports = loadStrings("balance.txt");
  String[] numbers = split(imports[0],',');
  coins = int(numbers);
}

String calc(int gold, int silver, int copper){

  for(int i = 0; i <= copper; i++){
    if(copper>9){
      copper=copper-10;
      silver++;
    }
  }

  for(int i = 0; i <= silver; i++){
    if(silver>9){
      silver=silver-10;
      gold++;
    }
  }

  fill(#F5EE0A);
  ellipse(20,20,10,10);

  fill(#AFAFAF);
  ellipse(20,45,10,10);

  fill(#AA5C46);
  ellipse(20,70,10,10);

  fill(#000000);
  text(gold + " Gold",30,25);
  text(silver + " Silvers",30,50);
  text(copper + " Coppers",30,75);

  return gold + "," + silver + "," + copper;

}

Upvotes: 0

Views: 162

Answers (1)

David
David

Reputation: 219037

If you use a debugger, you can stop on that line and see which object is actually null. If I were to guess, it's probably total[0] because I don't see where you initialize that.

You declare it here:

String[] total;

But you never initialize it to a value. That declaration line doesn't tell the compiler, for example, how many elements the array should have. So it doesn't have any. But then you try to access an element:

total[0] = ...

total[0] is the first element in an array that has no elements, therefore it doesn't exist. Contrast this to where you initialize some other arrays:

String[] imports = loadStrings("balance.txt");
String[] numbers = split(imports[0],',');

The methods loadStrings() and split() presumably return valid arrays, so imports and numbers are assigned the values of valid arrays. total is never assigned such a value.

Upvotes: 1

Related Questions