Can you find the index of the last "used" space in an array?
807601Feb 12 2008 — edited Feb 13 2008I'm getting back into Java after a long time away programming in other languages, and find myself having to relearn what small amount I once knew.
Currently I'm just trying to get to a point of being able to do the rudimentary logic, including looping that I'm used to.
My preference is to run a loop that does a countdown instead of a countup while looping over elements in an array.
So essentially, I'm trying to do is this:
public void failure()
{
int[] manyElements = new int[100];
manyElements[0]=56;
manyElements[1] = 5;
manyElements[2] = 23;
manyElements[3] = 82;
int i = manyElements.length; // *** Using .length causes the upper nulls to be hit and it errors out.
while (i>=0)
{
System.out.println(manyElements);
i--;
}
}
I realized after a lot of searching that I can a countup and a check for null:
public void testArrayTesttoString()
{
int[] manyElements = new int[100];
manyElements[0]=56;
manyElements[1] = 5;
manyElements[2] = 23;
manyElements[3] = 82;
int i = 0;
while (i>0)
{
if (manyElements[i] != null) // *** Err, this line also won't compile for some reason that I can't discern. Ugh.
{
i++;
}
else
{
break; // *** Break out of the loop when it starts to hit nulls.
}
}
}
I've just been frustrating myself trying to find the simplest way to use the simple syntax of arrays in a loop that ignores the amount of memory that the array has been allocated and pays attention to the actual number of elements instead.