java.lang.Exception: java.lang.ArrayIndexOutOfBoundsException: 7 - java

I am trying to store each line of a file into a String array.
/*
*Input file
*2 1 1 1 1 1 1.33 1
*4 2 15 3 9 3 0.185
*/
String[][] data_array = new String[1][7];
int i = 0;
int j = 0;
//file read
StringTokenizer tokenizer =new StringTokenizer(line,delim);
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
data_array[i][j] = token;
j++;
}
But showing
java.lang.Exception: java.lang.ArrayIndexOutOfBoundsException: 7
But When I am trying with
String[][] data_array = new String[1][8];
I am not getting this exception instead I am getting below as the output.
2 1 1 1 1 1 1.33 1 null
4 2 15 3 9 3 0.185 null

In java, arrays are 0-based, that is the first element will have index 0 and the last element will have index n - 1 (where n is the length of the array).
As your array is declared [1][7], the last index will be number 6. Your first row contains 8 values, therefore you end up trying to load the 8th value (index 7) into an array containing 7 elements. Using index 7 results in an IndexOutOfBoundException.
Moreover, in your particular case, the first row of the input contains 8 elements, but the second row only contains 7 elements. If you try to load 7 values into the array containing 8 elements, the last one will be null. For the input you specified, with array declared as having length 8, the output would be:
2 1 1 1 1 1 1.33 1
4 2 15 3 9 3 0.185 null
(Note that I added extra spaces to indicate better how the array is populated.)
Further, it makes little sense to declare a two-dimensional array with the first dimension being 1 - it's the same as declaring a single-dimension array. What you probably want to do is have an array with first dimension referring to rows in the file and second dimension referring to values in rows.

The elements of an array with length i are numbered 0 to i-1.
I assume you are using blanks as delimeters. Is there a trailing blank at the end of the line? This would explain why you are getting one surplus token.

you must use array in your method not in the body of your class!
and arrays first element have index=> 0 and the lastest element have index=> N-1

Related

How to take find the value attached to a specific index of an array

I have to return the value for a specific index of an array.
I am to take the last digit in my array and use that digit as the index for where to look in my array. Meaning if my array is 6543743 I need to return the value at the 3rd index, which should be 4. I have this so far, but it keeps returning 3 - it's taking the final index instead of going to that index for the value.
x = array[array.length-1];
I'm clearly missing something, but I can't figure it out. Thank you!
You need to subset the array twice:
int[] array = { 6 5 4 3 7 4 3 };
int num = array[array[array.length - 1]];
The last value in the array is given by array[array.length - 1], and then this value is used as an index again into the same array.

How can I optimize my code for Swapping the array elements of given range of indexes with related element?

Consider an array of integers A having N elements in which each element has a one- to-one relation with another array element.
For each i, where 1≤i≤N there exists a 1−>1 relation between element i and element N−i+1
The Task is to perform following operations on this array which are as follows:
Given two integers (L,R) we have to swap each element in that range with its related element.(See Sample explanation below)
Sample Input
5
1 2 3 4 5
2
1 2
2 3
Sample Output
5 2 3 4 1
Explanation
For first query,we will swap 1 with 5 and 2 with 4.
Now the array becomes- 5 4 3 2 1
Similarly now ,for the second query we will swap 4 with 2 and 3 with itself.
So the final array will be 5 2 3 4 1
My Program goes like this:
import java.util.Scanner;
public class ProfessorAndOps {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
int n=in.nextInt();//length of array
int a[]=new int[n];//array declaration
for(int i=0;i<n;i++){
//inputting array elements
a[i]=in.nextInt();
}
int q=in.nextInt();//number of queries
for(int i=0;i<q;i++){
int l=in.nextInt();//left limit
int r=in.nextInt();//right limit
//swapping while iterating over the given range of array elements:
for(int j=l-1;j<=r-1;j++){
int temp=a[j];
a[j]=a[n-j-1];
a[n-j-1]=temp;
}
}
//Printing the output array:
for(int i=0;i<n;i++){
if(i!=n-1){
System.out.print(a[i]+" ");
}
else{
System.out.println(a[i]);
}
}
}
}
I could only come up with BruteForce solution. I'm pretty sure there will be some pre-processing step or some optimisation technique with l and r variables, whatever I could think of, giving me wrong answer. Please help me optimise this code. To be specific, I would need my code's time complexity to be reduced from O(N+ Q*(R-L)) to something like O(Q+N)
Here's an O(Q + N) time, O(N) space algorithm. Imagine a list of the corresponding swap counts only for L and R over the elements (we'll use a negative number for the R counts). What if we maintained a virtual stack while traversing it? (By "virtual," I mean it's not a real stack, just an integer that bears some theoretical similarity.)
For example:
1 2 3 4 5 6 7 8 9 10
O(Q) processing:
q [1,3]
1 9 8 7 5 ... <- what would happen to the array
0 1 0 -1 0 <- counts (what we actually store)
q [2,4]
1 9 3 4 6 ... <- what would happen to the array
0 1 1 -1 -1 <- counts (what we actually store)
O(N) traversal:
index 0 didn't move, no change, stack: 0
index 1 moved once, odd count, changed, stack: 1
index 2 moved 2 (stack + 1), even count, no change, stack: 2
index 3 moved 2 (stack), even count, no change, stack: 2 - 1
index 4 moved 1 (stack), odd count, changed, stack: 1 - 1

Duplicate for-loop practice, beginner needs advice to study

Understanding the -1 in the for loop, need detailed explanation with for and if lines of code included?
int[] array = { 2, 5, 1, 2, 3, 5 };
Arrays.sort(array);
// why does this start counting from 1, and if l put 0 it goes to error, out of bounds?
for (int i = 1; i < array.length; i++) {
if (array[i] == array[i - 1]) { // - 1?
System.out.print(array[i]);
}
}
There is nothing inherently wrong with it.
It just makes the iteration to start with i=1 up to the array's length, but since indexing in arrays are zero-based you have to offset it when getting the value.
That is why is array[i-1]
If you put i=0 then you also have to change the ending condition to array.length-1, and you have to access the values by array[i] in order to avoid going out of bounds.
For questions like this, take the code one line at a time and try to follow what it is doing.
The first thing you do here is to create an array, then sort it. After the Arrays.sort(array) call, your array will contain the following:
index 0 1 2 3 4 5
----------------------
contents 1 2 2 3 5 5
Remember, arrays are zero-indexed - that means the very first element is located at index 0. (The contents of the array don't matter, it's the index you want to pay attention to.)
Arrays cannot have indexes less then zero, and they also cannot have indexes greater than their length-1. So, for your example, that means you cannot use -1 as an index because it is less than 0. You also cannot use 6 as an index, since 6 is greater than the length of the array (6) minus one.
In the initialization of the for-loop, you set i equal to 1 for the first iteration. Though unconventional, it's perfectly legal. This simply represents which index we will start from in the array. So for the first iteration of the loop, array[i] will be pointing to the value 2, and array[i-1] points to the value 1.
index 0 1 2 3 4 5
----------------------
contents 1 2 2 3 5 5
i ^
i-1 ^
Now, what if you set i to start at index 0 instead? Well, then array[i] will point to the 0th index (value 1)... but what does array[i-1] point to?
index 0 1 2 3 4 5
----------------------
contents 1 2 2 3 5 5
i ^
i-1 ^
It's pointing to index -1. Since arrays can't have indexes of -1, this is causing your IndexOutOfBoundsException. Hopefully that makes sense.

Why ArrayList giving unordered output?

I have written java program, to add integer in ArrayList and remove that integer from ArrayList . but it not giving me proper result. here is my code..
public static void main(String args[])
{
ArrayList<Integer> a=new ArrayList<Integer>();
a.add(6);
a.add(7);
a.add(8);
a.add(9);
for(int i=0;i<=a.size();i++)
{
System.out.println("Removed Elements=>"+a.remove(i));
}
}
it giving me output as follows
Removed Elements=>6
Removed Elements=>8
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.remove(ArrayList.java:387)
at CollectionTemp.main(CollectionTemp.java:19)
why i am getting output like this?
Your array:
a[0]=6
a[1]=7 <-- i
a[2]=8
a[3]=9
Then you remove at 1, and i increments to 2:
a[0]=6
a[1]=8
a[2]=9 <-- i
Remember that array indexes start at 0, so the last element is at a.length - 1
You get your exception because the loop condition i <= a.size(), so at the final iteration:
a[0] = 7
a[1] = 9
2 <-- i
When you remove items from a list, or any collection, you either use the iterator, or you use a reverse loop like this.
for (int i = (a.size() - 1); i >= 0; i--) {
System.out.println("Removed Elements=>" + a.remove(i));
}
By going backwards, you avoid the incrementing by 2 problem that has been documented in the other answers.
for first iteration, a.remove(i) causes the element 7 to be removed which is returned by remove method.
For second iteration, the size of list is 3 and you are removing the element at index 2 which is 9. SO remove method returns 9.
In short
Iteration | Size of list | index being removed | element removed
----------+--------------+---------------------+----------------
1 | 4 | 1 | 7
2 | 3 | 2 | 9
If you want a forward loop to remove all elements you could use the following code:
while(!a.isEmpty())
{
System.out.println("Removed Elements=>" + a.remove(0));
}
Your problem is that, as you remove elements, you resize the ArrayList. However, your loop counter is not updated, so you iterate past the bounds of the ArrayList.
ArrayList.remove(index) removes the element from the array, not just the contents of the ArrayList, but it actually resizes your ArrayList as you remove items.
First you remove the 1st element of the ArrayList.
Removed Elements=>6
Here the list has been resized from size 4 to size three. Now the element at index 0 is 7.
Next, you step to the element at index 1. This is the number 8.
Removed Elements=>8
Here the ArrayList has been resized to length 2. So there are only elements at index 0 and 1.
Next you step to index 2.
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.remove(ArrayList.java:387)
at CollectionTemp.main(CollectionTemp.java:19)
There is no index 2, so you get an IndexOutOfBoundsException.
the index starts with 0 and ends with size - 1
your loop goes from 1 to size - 2
ArrayList indexes start at zero, but your loop starts removing at 1. After adding the elements your arraylist looks like this:
0 - 6
1 - 7
2 - 8
3 - 9
Because your loop starts counting at 1, you will first remove the element labeled 1, which is 7.
The list will then look like this:
0 - 6
1 - 8
2 - 9
Then the loop will remove the element labeled 2, which is now 9.
So the two mistakes are starting at 1 instead of 0, and incrementing the counter after something has been removed (all elements after the removed element will shift down).
In the first iteration , i starts from 1, so your second element is removed ie. 7. Now list has
6
8
9
Next iteration is 2, so third element 9 is removed.
Your output is correct : Here is the explaination.
When the loop is executed for the first time, value of i will be 1. and it execute the statement a.remove(1). after removing the value 7 which is at place a[1], '8will be ata[1]'s place. After that i is incremented and becomes 2 and it removes the element a[2] which is 9.
This is simple logic:
First Iteration i=1:
a[0]=6,
a[1]=7,
a[2]=8;
a[3]=9;
Remove a[i] i.e a[1] removes 7
Second Iteration i=2:
a[0]=6
a[1]=7
a[2]=9
Remove a[i] removes 9
The value of i in the loop goes through the following values
0
1
2
3
4
The array has index with values 0 , 1 , 2 , 3
The loop will run for values 0,1,2,3,4
The array is not displayed ordered bcoz when one value is removed the next value is available at index 0
At i=2 , the size of array is 2 and max index is 1 , and hence IndexOutofBound exception is encountered
use the following loop :
while(a.size()>0)
{
System.out.println("Removed Elements=>"+a.remove(0));
}
whenever you remove an element from arraylist it deletes element at specified location.and this should be noted each time the size of arraylist decreases.
I dont understand what are you trying to remove. If you wan to clear list just call clear() method. If you are trying to remove objects contained in list, than you should know that ArrayList contains objects, not primitive ints. When you add them your are doing the following:
a.add(Integer.valueOf(6));
And there are two remove methods in ArrayList:
remove(Object o) //Removes the first occurrence of the specified element from this list
and the one you are calling:
remove(int index) //Removes the element at the specified position in this list
May be you should call first one:
a.remove(Integer.valueOf(i));

identifying .length in two dimensional array

What is the use of .length here? What could be substituted with .length in the code below? I just wanted to understand the code better, Exams tomorrow! W00t!
public class twoDimension{
public static void main(String[] args) {
int[][] a2 = new int[10][5];
for (int i=0; i<a2.length; i++) {
for (int j=0; j<a2[i].length; j++) {
a2[i][j] = i;
System.out.print(" " + a2[i][j]);
}
System.out.println("");
}
}
}
You have declared an array of arrays of int type and initialized it.
10 inside the first square bracket says that you are going to store 10 values for the row and is the size of the array ‘n’ where n=10. The row length is 10.
5 inside the second square bracket says that you are going to store 5 values for the column and is the size of the array ‘n’ where n=5. The column length is 5.
In this case, you have one array with 10 locations
streetX[house_1]
streetX[house_2]
streetX[house_3]
streetX[house_4]
streetX[house_5]
streetX[house_6]
streetX[house_7]
streetX[house_8]
streetX[house_9]
streetX[house_10]
and inside each of the location is another 5 different locations
{house_i[room_number1], house_i[room_number2], house_i[room_number3], house_i[room_number4], house_i[room_number5]}
where i can represent any of 1 to 10
Think of it as 10 houses on a street. Each of the houses having 5 rooms. Each house will have a unique address to distinguish it from other houses on the street. In the same manner, each room in one house will be different from the rest. You can now keep different stuffs in each room.
The street is has an array of houses and each house has an array of room.
Therefore, you will have: You can think of a2 as streetX, i.e. a2 = streetX
streetX has 10 houses, therefore, there are 10 locations in a2. The size of a2 is 10 meaning that the length is 10. Therefore, a2.length = 10
NOTE: When you refer the array values, the index starts from 0 ‘zero’ to ‘n-1′. An array index is always a whole number and it can be a int, short, byte, or char.
house_i (where i ranges from 1 t0 10) but we usually count the index from 0. We'll have index 0 to 9. house_i is similar to a2[i]. There are 5 rooms, hence 5 locations. The size of any a2[i] (i.e. any house a2[0], a2[1], a2[2], a2[3] or a2[4])) is 5 meaning that the length is 5. Therefore, a2[i].length = 5
a2[house1][room1] a2[house1][room2] a2[house1][room3] a2[house1][room4] a2[house1][room5]
a2[house2][room1] a2[house2][room2] a2[house2][room3] a2[house2][room4] a2[house2][room5]
a2[house3][room1] a2[house3][room2] a2[house3][room3] a2[house3][room4] a2[house3][room5]
a2[house4][room1] a2[house4][room2] a2[house4][room3] a2[house4][room4] a2[house4][room5]
a2[house5][room1] a2[house5][room2] a2[house5][room3] a2[house5][room4] a2[house5][room5]
a2[house6][room1] a2[house6][room2] a2[house6][room3] a2[house6][room4] a2[house6][room5]
a2[house7][room1] a2[house7][room2] a2[house7][room3] a2[house7][room4] a2[house7][room5]
a2[house8][room1] a2[house8][room2] a2[house8][room3] a2[house8][room4] a2[house8][room5]
a2[house9][room1] a2[house9][room2] a2[house9][room3] a2[house9][room4] a2[house9][room5]
a2[house10][room1] a2[house10][room2] a2[house10][room3] a2[house10][room4] a2[house10[room5]
NOTE: When you refer the array values, the index starts from 0 ‘zero’ to ‘n-1′. An array index is always a whole number and it can be a int, short, byte, or char.
If n = 10, we'll have 0 ... 9
If n = 5, we'll have 0 ... 4
As an example, streetX[house1][room1] = a2[house1[room1] will become a2[0][0]
Eventually, you will have:
a2[0][0] a2[0][1] a2[0][2] a2[0][3] a2[0][4]
a2[1][0] a2[1][1] a2[1][2] a2[1][3] a2[1][4]
a2[2][0] a2[2][1] a2[2][2] a2[2][3] a2[2][4]
a2[3][0] a2[3][1] a2[3][2] a2[3][3] a2[3][4]
a2[4][0] a2[4][1] a2[4][2] a2[4][3] a2[4][4]
a2[5][0] a2[5][1] a2[5][2] a2[5][3] a2[5][4]
a2[6][0] a2[6][1] a2[6][2] a2[6][3] a2[6][4]
a2[7][0] a2[7][1] a2[7][2] a2[7][3] a2[7][4]
a2[8][0] a2[8][1] a2[8][2] a2[8][3] a2[8][4]
a2[9][0] a2[9][1] a2[9][2] a2[9][3] a2[9][4]
The outer for...loop will be repeated 10 times, remember, a2.length = 10 and the inner for ... loop is repeated 5 times, remember, a2[].length = 5
You initialized a2[i][j] = i, therefore for each inner loop, you will have the index of i (the house) will be the stored as the value or number of things in each room for the house.
Hence, when you execute the program, you will get the output or result below printed out.
Count the number of rows and columns and observe that on each line the values are the same.
0 0 0 0 0
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
6 6 6 6 6
7 7 7 7 7
8 8 8 8 8
9 9 9 9 9
For an array you can use [array_object_name].length or specify the size in number. E.g. a2.length or 10, or a2[i].length or 5 in you example program. Where i equals any of 0, 1, 2, 3, 4. Note that length in .length is a static variable ( You can read more about static variables from here http://download.oracle.com/javase/tutorial/java/nutsandbolts/variables.html and learn about static methods and static classes as well)
In summary, the length is the size of an array
You can learn more about array from here - http://javapapers.com/core-java/java-array/
What is the use of .length here?
no different from one dimensional array: to get number of elements in the array, if you treat two dimensional array as a table, then assuming the first .length is the row length, the second .length is the column length. get it?
What could be substituted with .length in the code below?
What do you see in the declaration (construction to be precise)?
a2.length is the number of rows. In this case the outer loop will iterate 10 times.
a2[i].length is the length of one specific row.

Categories