Hi,

I have initialized an array like this:

int[][] my_array= new int[28][28];
my_array[-6][12]=2;

But when i assign my_array with my_array[-6][12] it is giving me error.I know the doubt is very stupid but I am very confused.
I want to store values in an array which has negative as well as positive indexes.Is there any other way i can do it?

no. Indices always start at 0. ALWAYS. At least thats what I have noticed.

Previous poster is absolutely correct. Absolute index of an array arr[] must be in the range [0..arr.length-1] - can't be negative, can't be equal to or greater than the length.

Notice I say "absolute index" - that's the index that the compiler sees as the value. Now, suppose you want your array to map values to points on a number line, and your number line ranges from -10 to 9, inclusive. That's 20 places, so you declare an array of 20 ints. You can then figure that what the compiler thinks is 0 corresponds to your -10, and so forth, so when you calculate the values for y at each place on the number line, you just iterate i from 0..20 and calculate the value of array using i-10 as your x value.

Easy peasy. Just make sure you keep track of when you want the index (i) and when you want the position on the number line (i-10).

I'm not sure what exactly you've got in mind, but that example might help with whatever you're trying to do.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.