Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Java (http://www.programmingforums.org/forum17.html)
-   -   last element trouble (http://www.programmingforums.org/showthread.php?t=11661)

NightShade01 Oct 21st, 2006 11:05 PM

last element trouble
 
I'm working on these little programming projects for a class (via the internet) and i'm stuck on one of them. The question is:

Given that an array named "a" whose elements are of type int has been declared, assign the value
********* -1
to the last element in a .

I was doing: a.getLength - 1 = -1;

but i'm getting an error. I tried adding a[].length - 1 but i still get an error saying something has to be in the brackets.

Dameon Oct 21st, 2006 11:15 PM

[] means index.

When you wrote a[].length, you didn't actually want to index anything. You wanted to take the array and get its length, not the "length" of some (in this case illegaly unspecified) element.

To elaborate, a is the array itself, a[insert an index] is an element in the array. So to get the length, that would be a.length. Length is common to all arrays and tells you the number of elements.

As you correctly concluded, since arrays start at 0, the last element is array length minus one.

Combining those two statements you get a[a.length - 1] to get or set the last element. However, note that if the length is 0, the resulting index would be -1, which would throw an exception (There's not a last element in an empty array anyway, but nobody likes crashes...check for this case).

:

a[a.length - 1] = -1;

NightShade01 Oct 22nd, 2006 8:40 AM

haha wow I feel stupid reading your post I feel like that answer should have been common sense... lol Thanks


All times are GMT -5. The time now is 12:58 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC