Matt Gerrans
Posts: 1153
Nickname: matt
Registered: Feb, 2002
|
|
Re: LinkedList
|
Posted: Oct 1, 2003 11:57 AM
|
|
Here's a quick tutorial on 0-based indexing: If an array has 5 items, the indices of these items will be 0, 1, 2, 3, 4 and the length of the array will be 5. The last item in the array is at index 4 (or array.length - 1 ), not 5.
You increased your array size to 11, making it possible to index it (incorrectly) from 1 to 10 without a crash, but then you shot yourself in the foot by also using array.length, assuring that it will always fail, even if you increase the size to 12, 13, or all the way up to Integer.MAX_VALUE.
Using array.length was a good idea, but starting at 1 and comparing with "<=" instead of "<" are both bad ideas in Java. You want to start indexing at 0 and stop before you get to array.length.
Here's a little example you can experiment with. (By the way, since it looks like you are still just learning the fundamentals of Java, you might want to experiment with smaller programs to try and focus on specific concepts, so you don't get overwhelmed by lots of different things at once).
class arraystuff
{
public static void main(String args[])
{
String [] array = {"Null","Ein", "Zwei", "Drei", "Fier" };
System.out.println( "There are " + array.length + " items in the array:" );
for( int i = 0; i < array.length; i++ )
System.out.println( i + ". " + array[i] );
}
}
Look closely and notice that indexing starts from 0 and stops before hitting array.length.
The output of this program will be:There are 5 items in the array: 0. Null 1. Ein 2. Zwei 3. Drei 4. Fier
By the way, please use the java tags when posting code! It makes the code in the post much more readable. It is quite easy to do; here's an example: [ java ]for( int i = 0; i < array.length; i++ )
{
...
}
[ /java ]
|
|