I have two programs. I create a static array and some methods such as the following:
public Someclass{
static int counter[] = new int[n];
//methods & main
}
the n is defined to be some number, so I know it will have some length. I later fill this array and I test to see that it gets filled correctly, so I know some indexes should have values other than 0. Now when I try to call it in second program, it is though I never filled it because it only gives me 0's.
//second program
public Someclass2{
public static main(String[] args){
String n = "someword"
int[] nums = new int[n.length]
for( int i = 0; i < n.length; i++){
nums[i] = nums[i] + (25 * SomeClass.counter[i]);
}
}
}
For some reason, when I call the array in the second program it returns all zeros and doesnt change the value of nums, even though I know the counter array should have non-zero values. I think it has to do with the fact that I initialize it statically but I filled it in a local method and in the class. So techincally it never gets it's zeroes updated. I am having trouble trying to fix this and if anyone could help I would aprreciate it.
Thank you
My guess: you're filling the array inside of SomeClass, but never call that filling code before using the array in the other class. Solution: be sure to fill it first. For more specific help, show us more details about your code.
Other points -- it is usually best to avoid use of static fields, and instead it is usually better to make the array an instance field. Then you can ascertain its state through its containing class, and also change its state through the containing class with any restrictions that you'd like to put on the ability to change it.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments