Given an Integer array (global/static) defined within my Class scope, I want to be able to use the integer array from within any function in the class itself. However I seem to be having issues accessing the array, what I do is I Initiallize (define the size) the array 1st thing in my main, then later in another function (StartConf) I want to use the array. My goal is to increment a value in the array when this function is run (for a specific index).
public class Main {
public static int[] confArray;
public static void main(String[] args) { // Each Indexed Integer corresponds to the amount of users in that channel/topic int confArray[] = new int[10]; // I need to INITIALIZE the array = 0 here, currently I can only do it manually confArray[1]=0, etc... .. DO SOME STUFF .. StartConfs(); }
public static void StartConfs() { confArray[0] = 0; // THIS FAILS, nullexceptionpointer confArray[0]++; // THEN OF COURSE THIS FAILS } [Code]
So I have 2 major issues: 1- I need to Initialize my int[] = 0 (so I am sure my counters start at 0) 2- I need to be able to access it from inside the StartConf function
Currently if I debug through the code I can see that in my main the int[] is created (still not 100% on the best way to initialize the entire thing = 0) However my StartConf function sees it as a NULL int[] (as if it was not created) and generates errors like "nullpointerexception" because the int[] is null (but I initialized it in my main) I am trying to use this as a "global variable", am I doing something wrong? Any help would be appreciated, Thanks,
Your problem is that you use 2 different arrays with the same name.
publicclass Main {
publicstaticint[] confArray;
publicstaticvoid main(String[] args) {
int confArray[] = newint[10]; //this variable overrides the variable in the class
//.. DO SOME STUFF ..
StartConfs();
}
publicstaticvoid StartConfs() {
confArray[0]++; //confArray was never initialized.
}
Change the line in the main method to:
confArray = newint[10];
All numerical variables in an array are 0 by default. You could allways do this:
for (int i = 0; i < confArray; i++)
confArray[i] = 0;
or (starting with Java 1.5):
for (int num : confArray)
num = 0;
I'm nut sure if it will work, since int is a primitive type and I don't know if num would only be a copy of the array content.