I am sure that I'm the first one, but when I create a Java program:


Code:
 public class Name
{
public static void main(String[] args)
{
int[] array;
array = new int[10];
int s=1;
while(thisistrue())
{
array[s]++;
s++;
}
}
}

it throws this error:

Code:
 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10

I am wondering how to fix it and why this is happening.

EDIT: This program was fixed by me. To anyone having this problem, you need to move

Code:
 s++

out of the while loop.
So the code will look like this:

Code:
 public class Name
{
public static void main(String[] args)
{
int[] array;
array = new int[10];
int s=1;
while(thisistrue())
{
array[s]++;
}
s++;
}
}
What are you trying to accomplish? Where is thisistrue() defined? Right now you're incrementing the second element in array[] for a while, and then incrementing s once. Arrays in java are 0-indexed, which means array[0] points to the first element, which means array[9] points to the 10th element, and array[10] overflows the length of the array. This is exactly what the error message is telling you:

  • Exception in thread "main" - Something blew up. You're not using multiple threads, so the second bit doesn't matter.
  • java.lang.ArrayIndexOutOfBoundsException: - What blew up? Well you gave it a number that points outside of the array.
  • 10 - which number? 10.
  
Register to Join the Conversation
Have your own thoughts to add to this or any other topic? Want to ask a question, offer a suggestion, share your own programs and projects, upload a file to the file archives, get help with calculator and computer programming, or simply chat with like-minded coders and tech and calculator enthusiasts via the site-wide AJAX SAX widget? Registration for a free Cemetech account only takes a minute.

» Go to Registration page
Page 1 of 1
» All times are UTC - 5 Hours
 
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum

 

Advertisement