ArrayIndexOutOfBoundsException when iterating through all the elements of an array - java

how to handle this exception "ArrayIndexOutOfBoundsException"
my code : I create an array of 64 length then I intialized every index then I print the indexes to make sure I am fulling all indexes but it prints up to 63 then gives the exception !! any idea
public static void main(String [] arg) {
int [] a=new int [64];
for(int i=1;i<=a.length;i++){
a[i]=i;
System.out.println(i);
}
}

The array indexes in Java start from 0 and go to array.length - 1. So change the loop to for(int i=0;i<a.length;i++)

Indexes start from 0 so last index is 63. Change your for loop like this:
for(int i=0;i<a.length;i++){

See the JLS-Arrays:
If an array
has n components, we say n is the
length of the array; the components of
the array are referenced using integer
indices from 0 to n - 1, inclusive.
So you have to iterate through [0,length()-1]
for(int i=0;i<a.length;i++) {
a[i]=i+1; //add +1, because you want the content to be 1..64
System.out.println(a[i]);
}

Need Complete Explanation? Read this
The index of an Array always starts from 0. Therefore as you are having 64 elements in your array then their indexes will be from 0 to 63. If you want to access the 64th element then you will have to do it by a[63].
Now if we look at your code, then you have written your condition to be for(int i=1;i<=a.length;i++) here a.length will return you the actual length of the array which is 64.
Two things are happening here:
As you start the index from 1 i.e. i=1 therefore you are skipping the very first element of your array which will be at the 0th index.
In the last it is trying to access the a[64] element which will come out to be the 65th element of the array. But your array contains only 64 elements. Thus you get ArrayIndexOutOfBoundsException.
The correct way to iterate an array with for loop would be:
for(int i=0;i < a.length;i++)
The index starting from 0 and going to < array.length.

In Java arrays always start at index 0. So if you want the last index of an array to be 64, the array has to be of size 64+1 = 65.
// start length
int[] myArray = new int [1 + 64 ];

You can correct your program this way :
int i = 0; // Notice it starts from 0
while (i < a.length) {
a[i]=i;
System.out.println(i++);
}

You've done your math wrong. Arrays begin counting at 0. E.g. int[] d = new int[2] is an array with counts 0 and 1.
You must set your integer 'i' to a value of 0 rather than 1 for this to work correctly. Because you start at 1, your for loop counts past the limits of the array, and gives you an ArrayIndexOutOfBoundsException.

Related

Why this for loop of array uses newARRAY.length-1?

Hello I'm beginner at java now I've arrived to arrays here is a for loop to sort number from highest to lowest, my question is why the instructor used
newARRAY.length-1
?
public static int [] integers;
public static int [] sortArray(int[] array){
boolean PeaceArray = true;
int temp;
int [] newARRAY = Arrays.copyOf(array,array.length);
while(PeaceArray){
PeaceArray = false;
for(int i=0;i<newARRAY.length-1;i++){
if(newARRAY[i]< newARRAY[i+1]){
temp = newARRAY[i];
newARRAY[i] = newARRAY[i+1];
newARRAY[i+1] = temp;
PeaceArray = true;
}
}
}
return newARRAY;
}
Normally the first index of a java array starts from zero (0), but the length property of
the arrays gives an actual count of the array.
For example, consider the following integer array:
int[] numbers = {40, 55, 63, 17, 22, 68, 89, 97, 89}
This array can be represented graphically as well like below
So if we are to run a loop for this array like:
for(int i=0; i<numbers.length; i++){
//this loop runs 9 times
}
I the above loop i was initialized to 0 and the maximum value i can get to is 8 but the loop will run 9 times because if you count all the way from 0 to 8 you get 9
But if you run a loop like this
for(int i=0; i<numbers.length-1; i++){
//this loop runs 8 times
}
The loop will run 8 times but the maximum value i can get to is 7
Your instructor used newARRAY.length-1 because he didn't want the maximum value of i to exceed the immediate lower number following newARRAY.length-1 because he was using the value of i+1 to index the array newArray somewhere in the code.
If he hadn't used newARRAY.length-1 in the code, when i gets to its maximum value, newARRAY[i+1] would give an IndexOutOfbounds error, because the last index of newARRAY would have been exceeded because of the 1 he is adding to i to access the newARRAY
I hope you understood this.
Array start the index with 0
ex:
int a[]={1,2,3,4,5};
then a.length=5 but a[5] does't exits in the array
a[0]=1
a[1]=2
a[2]=3
a[3]=4
a[4]=5
for this reason we use a.length-1 instead of a.length

how to iterate over consecutive pairs in arrayList

I want to create a loop that iterates through an ArrayList of objects.
for (int i = 0, k=i+1; k < arr.size(); i++) {
int tprice;
tprice=0;
if (arr.get(i).getID()=arr.get(i+1).getID()) {
tprice = arr.get(i).getPrice() + arr.get(i+1).getPrice();
}
else {
if (tprice!=0) {
System.out.println(tprice);
}
else {
System.out.println(arr.get(i).getDuration());
}
}
}
I want to compare element i to element i+1 of the ArrayList, without creating a nested for loop as I am not interested in all the permutations. (e.g, 1->2 then 2->3, not 1->2 then 1->3)
However, my line of code always causes an error because index k at the end of the loop is referencing an out-of-bounds index (or the equivalent for ArrayList).
Say i have three arrays : i=0 compares to i=1, i=1 compares to i=2, i=2 compares to i=3 but throws back an error since it doesn't exist.
Is there any way to overcome this? It seems silly, but I couldn't find anything about it across the forums.
exemple hardcode:
arr.add(new object(444,24)) // 444 is ID, 24 is Price
arr.add(new object(444,29)) // 444 is ID, 29 is Price
arr.add(new object(121,33)) // ...
wanted outcome :
53
53
33
side-question : if i am dealing with the same ID, i would ideally wish to print only once. Is there anyway to do so?
If you touch the two consequent elements of the array, you have to stop one element before you read the end:
for (int i = 0; i < arrayList.size() - 1; i++) {
// do stuff with arrayList.get(i) and arrayList(i+1)
}
Of course, the arrayList must contain at least two elements otherwise the loop will never be entered since the arrayList.size() - 1 would be equal to 0.
Moreover, you confuse arrays with ArrayList<T>.
List<T> of size list.size() has methods list.add(T t) and list.get(int index).
An array int[] array of size (length) array.length access to items with index array[0].
If all you want to check is the adjacent elements in the array, just start from the index 1 till the end and compare the adjacent: current and previous.
for (int i = 1; i < arr.size(); ++i) {
if (arr.get(i) > arr.get(i-1)) ....
}

Sort an array as values are inputted into the array

I need help with a loop that will shift the elements of an array if a newly added value is lower than an existing value, so the array is being sorted as new values are inputted.
The array is empty to start with.
I had tried several loops but they don't seem to work in my case as they were loops used for arrays that were already full.
Here is the code I currently have.
if(index < 0)
index = -(index + 1);
if(arr[index] > key)
for(int i = 0; i < count -1; i++) {
arr[index + i] = arr[index + i + 1];
}
arr[index] = key;
The index is from a binary search.
So for example, if I have input 80 first, it would take the slot of arr[0]. Then I input 45, which will also take the slot of arr[0].
Since 45, key, is smaller than the existing arr[0] (80), 80 is to move up an index.
You might want the loop so that it does the following:
Shift the elements with indices > index so that you make space for the new element, and
then add the element to given index.
for (int i = count; i > index; i--) {
arr[i] = arr[i - 1]; // shifts the elements to the one place right
}
arr[index] = key; // add the key to the given index
Note: The count is the current number of elements in the array and it is less than arr.length
You can go for something like this:
First of all, you need
A counter that tells you how many "unused" array elements are left; there is no point in swapping index 1 to 2, 2 to 3, ... if you find in the end that your array is "full"
Keep an eye on the index, to avoid going beyond the length of your array
Then it is really simple:
You iterate your current array to find the first index (lets call it n here) that is bigger than key
Then you turn to the last array index that is "in use" ... and start moving values to the right from there
Finally, after you moved arr[n] to arr[n+1]; you assign arr[n] = key
It looks like you're attempting to shift your array elements in the wrong direction.
Given index = 0 and i = 0, you'd end up with:
arr[0] = arr[1];
When you probably want the other way around.

Remove the previous and next element of the middle element in an array and shrik the array using Java

I have an array say n elements
I put the array to an array list. And i find the middle index and remove the previous and next element of the middle element..
For instance if my array has 6 numbers
{1,2,3,4,5,6}
I find the middle element ie 4 and remove 3 and 5. Now my array should shrink and run the loop till the array gets empty. How do i do this?
This is my code
Scanner in=new Scanner(System.in);
int t=in.nextInt();
System.out.println("t value"+t);
int n=in.nextInt();
System.out.println("n value"+n);
int arr[] = new int[n];
for(int i=0;i<n;i++){
arr[i] = in.nextInt();
System.out.println("a[j]"+arr[i]);
}
ArrayList<Integer> obj = new ArrayList<Integer>();
int count=0;
for(int k=0;k<n;k++){
obj.add(k,arr[k]);
}
//int m = in.nextInt();
//System.out.println("m value"+m);
for(z=0;z<n;z++){
int middleIndex = (arr== null || arr.length == 0) ?
-1 : arr.length / 2;
System.out.println("middle"+middleIndex);
obj.remove(middleIndex-1);
obj.remove(middleIndex+1);
--n;
System.out.println(arr[z]);
}
}
}
I get the following error:
t value1
n value6
a[j]1
a[j]2
a[j]3
a[j]4
a[j]5
a[j]6
middle3
[1, 2, 4, 5]
middle3
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 3
at java.util.ArrayList.rangeCheck(ArrayList.java:604)
at java.util.ArrayList.remove(ArrayList.java:445)
at TestClass.main(**.java:46)
And also here its removing my middleIndex-1 and middleIndex+2 element. I want to remove only the previous and next element of the array to be removed.
Your problem is that you are removing elements from ArrayList variable obj whereas you are calculating the middle based on the int array variable arr which does not change in length after removal of elements. So in your example in the second loop the middleIndex is 3 but the size of obj is 4. now if obj.remove(middleIndex+1); is called it means obj.remove(4) which throws the IndexOutOfBoundException.
Also there is a problem with your removal loop. You have used a new variable z it starts from 0 and continues to n, as shown in your example to 6 here. But the problem is that after the first loop the length of the obj is 4, after second loop the obj size is 2, and after 3rd loop the size becomes 0. so what is the utility of looping after that? would it not be better if
You could solve this by making a change as below:
while(obj.size()>0){
int middleIndex = (obj.size() == 0) ?
-1 : obj.size() / 2; // replace the arr variable with obj.
System.out.println("middle"+middleIndex);
obj.remove(middleIndex-1);
obj.remove(middleIndex+1);
--n;
System.out.println(arr[z]);
}
You are using the size of the wrong object, you need to use obj instead of arr, and make sure the elements exist before trying to remove them.
Something like this would solve these problems:
for(int z=0;z<n;z++){
int middleIndex = (obj== null || obj.size() == 0) ?
-1 : obj.size() / 2;
System.out.println("middle"+middleIndex);
if (middleIndex-1>0)
obj.remove(middleIndex-1);
if (middleIndex+1<obj.size())
obj.remove(middleIndex+1);
--n;
System.out.println(arr[z]);
}

counting occurrence of 2d array in java

This is the question i am trying to solve:
Write a class called ArrayHistogram, which contains a main method and a static method called histogram, which has the following signature:
public static int[] histogram(int[][] arrayA)
In the main method, declare and initialize a two dimensional array, call it arrayA. This array must contain some non-negative integer numbers. The histogram method accepts arrayA and puts the frequency of occurrence of elements of arrayA into a one dimensional array (histA) and returns histA. Frequency of occurrence means, the number of times an element occurs in the array. Your program should work for a ragged array, as well. Your program should determine the size of the histA automatically, before declaring the variable histA.
Hint: Figure 1 shows a sample 2D array(arrayA) and the corresponding histA. histA[0] = 2 shows that 0 occurred twice in A. Or, histA[3] = 1, shows that number 3 appeared once in A.
I have done this so far
public class ArrayHistogram
{
public static void main (String[]args)
{
// declearing and initializing a 2D array.
int [][] arrayA = {{5,8,8,4,3},{1,4,2,2,3},{7,4,6,6,9}};
histogram(arrayA);
}
public static int[] histogram (int [][] arrayA)
{ // nested for loop to go through the array.
int max = 0;
for ( int row = 0; row<arrayA.length; row++){
for ( int col=0; col < arrayA[row].length; col++){
if ( arrayA[row][col]> max ){
max = arrayA[row][col];
}
}
}
int histA[] = new int [max];
for ( int row = 0; row<arrayA.length; row++){
for ( int col=0; col < arrayA[row].length; col++){
histA[arrayA[row][col]]++;
}
}
System.out.println(histA);
return histA;
}
}
This line:
histA[arrayA[row][col]]++;
shows a java.lang.ArrayIndexOutOfBoundsException
First am I doing this right?
If not how should I make it happen?
Keep in mind that arrays are indexed starting at 0, so your max value is not going to be an index available in your histA array. One way to fix this is create your array like so:
int histA[] = new int[max + 1];
In your second loop, when you hit row being 2 and col being 4 it's going to attempt to use histA[9] which isn't a valid index in that array unless you define your array to be of size 10, which in your case is max + 1.
length is an attribute of array objects which returns the size. Now since you are looping your array starting from 0 to the length of array, its referring to the index of array which doesn't even exists. Hence an ArrayIndexOutOfBoundException.
Just update your for loop termination expression to arrayA.length-1 and arrayA[row].length-1 and it will all be working fine.
Also for all such exceptions just check their Java Doc and you will get your answer.

Categories

Resources