Link to home
Start Free TrialLog in
Avatar of kengoudsward
kengoudsward

asked on

how to stop "array may not be initialized" warning


my class has an array of ints named "calls" and an int "calls_size" to keep track of it's size. I know this screams for a Vector but I think it is a pain in the butt using a vector for ints, too much screwing around with Object nonsense

anyway, this function should return an array of ints matching "calls" but with "calls_size" at the begining, so if calls==10,11,12 then results=3,10,11,12

it has been awhile since I have used java, especially with arrays, so I'm not sure if my whole open ended array idea will work, but at any rate, line 06 gives me a compilation error:  "variable results might not have been initialized".
I am quite aware of this fact and I don't care if it is initialized or not since I am manually tracking the size. This error stops compilation, however. Is there any way to demote the error to simply a warning? Any suggestions regarding my scheme would also be welcomed.

01 public int[] getCalls()
02 {
03    try
04    {
05        int[] results;
06        results[0] = calls_size;
07        for(int i = 1; i <= calls_size; i++)
08        {
09            results[i] = calls[i];
10        }
11        return results;
12   }
   ...snip ...

Thanks,
Ken Goudsward
Avatar of Mick Barry
Mick Barry
Flag of Australia image

int[] results = new int[calls_size+1];
You have to declare the size of the array.
You can actually get the size of an array using:

myarray.length
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of kengoudsward
kengoudsward

ASKER

Thanks guys,
can't test it today, but...
I like that wrapper class solution!
I will also try putting the array declaration before the 'try' block
> I will also try putting the array declaration before the 'try' block

That won't help. Even if you get rid of the compiler error you'll get a NPE at runtime.

http://www.objects.com.au