When I declare an array in java I get this error when running: Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException. Despite that the variable totalNumbers has a value. It’s working when I replace that variable into a number like 5. Must it be a number when declare array?
int randomNumbers[];
randomNumbers = new int[totalNumbers];
Added some more code, but’s the variable names and comments are in swedish! But perhaps the code could be understodd despite of that!? Or why not learn some swedish!= 🙂
// deklarera arrays för tal under 500 och för tal över 500
int slumptalMindre[];
slumptalMindre = new int[antalSlumptalMindreÄn500];
int slumptalStörre[];
slumptalStörre = new int[antalSlumptal - antalSlumptalMindreÄn500];
//gå genom första array och omplacera tal till ny array
for(int x = 0; x < antalSlumptal; x++) {
if(slumptal[x] < 500) {
slumptalMindre[x] = slumptal[x];
}
}
You did not post what values are possible for
antalSlumptalMindreÄn500andantalSlumptal, but according to your code I assume both are positive andantalSlumptal>antalSlumptalMindreÄn500.I.e. let antalSlumptal = 20 and antalSlumptalMindreÄn500 = 5.
Then the length of array slumptalMindre is 5 and the length of slumptalStörre is 15. But there is no declaration of array
slumptal.In your for loop variable x ranges from 0 to 19 and in each iteration you access array
slumptalMindrewith index x. Apparently this leads to an ArrayIndexOutOfBoundsException when the x-value becomes 5.I can only guess what your intention was. It seems that you want to apply some filter on array
slumptaland put all values less than 500 in another array.One problem in using an array for the filter result is, that you don’t know the length of the result after the loop is finished. But you have to initialize the array beforehand.
So one solution could be the usage of two loops. The first iterates through the array and counts how many numbers are less than 500. Then you initialize your array with the right size and the second loop iterates over the array again and copies the result values to the result array. In the second loop you have to be carefull to distinguish between the index to access array slumptal and the index to access the shorter result array:
But the solution above is not optimal because you have to iterate through the array twice. This only because the result should be a fixed length array. It is easier to use a dynamically sized data structure like a
Listin this case:One more hint about coding style: It is valid to use Umlauts in variable and class names in Java. But doing so is considered as bad style because you can easily run into problems. The Java compiler uses the platform default encoding for the source files unless you specify the
-encodingoption. On Windows the default encoding is Cp1252, on Linux usually UTF-8. Things went worse if Umlauts are part of class names because this leads to class file names containing Umlauts.