JAVA Array index out of bounds even though < array length [duplicate] - java

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
The Array containing the object's details is out of bounds. It would say "Index 1 out of bounds for length 1". However When I printing the strings and arrays and it seems to be captured. Even the array lengths are 3 not 1, but still the error persists
Also, initially, I was able to make this work by putting columns.split("\s+") but after a few runs it went back to this Index 1 out of bounds for length 1....
See Image to see how the problem looks.
What did I miss?
Added Println statement to see what it reads per line.

This line is giving error :
String toUnit = columns[1];
I think the value at this index doesn't exist, i.e, the array size is 1.
Possible Root cause : The split is not properly happening or if you are splitting the value, only one value is extracted.
Check the file whether you have set the value or not so that it should be there in the array. Otherwise, you will get that error.

In the while loop, you should print the line before you split it, so that you know what the line contains.
As Nick already suggested, maybe the line is blank or it does not have the FIELD_SEP as per what you expect.

I think you need to check your conversionsFile and somwhere in that file, there might be a line where it will be having only one value/column (i.e not a proper data) instead of having all the three values.

Related

ArrayList/LinkedList get First Index number

Is is possible to get out of an ArrayList the first number of the first index?
Here's an Example:
In there are 5 items:
path = {0.5,5.0},{0.6,6.0},{0.7,7.0},{0.8,8.0},{0.9,9.0}
And I want to get the number 5.0 out of {0.5,5.0}...
I tried it with path.get(0) But it only gives me {0.5,5.0} back.
Is it possible to get 5.0 out of it without getting all the other numbers?
If your ArrayList contains arrays, this is the way to go
myList.get(0)[1] // You're getting the index 1 from the 1st array of your ArrayList
Otherwise, if it is containing other ArrayList's
myList.get(0).get(1) // Same logic as above applied to the Collection
If your curly braces in the ArrayList are actually brackets (they probably are), you can use:
myArray.get(0)[index] to get the index you want. In your example it is:
myArray.get(0)[1];
Note: if your ArrayList elements are also ArrayList then you need to use get(0).get(1) instead of get(0)[1].

Why did the first for loop fail in Java? [duplicate]

This question already has answers here:
Why does the foreach statement not change the element value?
(6 answers)
Closed 7 years ago.
I have a int[] a, and trying to set every element in the a to be 1. So when I did following code, and printed every element, it shows they are still 0s.
for(int num:a)
num=1;
But if I try below, every element is 1 now. I'm confused. I always thought the 2 for loop have the same functionality. Can anyone tell me why my first try failed? And why it works when i print them? Thanks~~~
for(int num=0;num<a.length;num++)
a[num]=1;
for(int n:a)
System.out.println(n);
Your first loop declares a local variable which only exists inside that loop. Its value iterates over every value in the array. A new memory location is reserved temporarily and given the name "num". Changing contents of that memory location does not modify the values in the "a" array.
Your second loop explicitly accesses memory allocated for the array "a" and changes their contents.
These loops are different. Both in functionality and operations.
The first one - an enhanced-for loop - is giving you each element in the array referenced by the variable a. It is not exposing anything for you to mutate, so assignments to a have no effect on the actual value in the array.
The second loop is simply going through all of the elements in the array, but you are directly working with the array itself at all times, so mutating the values is perfectly possible.
To put this in other terms:
The enhanced-for is going through the array, and providing you a value to use. That value, while originally provided by the array, has no connection to the array otherwise. Any modifications made to the value would not propagate to the array.
The alternative loop is only ever accessing the array contents directly, where it is perfectly possible to make modifications and reassignments to the array.
Thus, if you ever want to set the values of an array to anything other than their default value, then using the second approach is the way to go.
Or...you could use Java 8's Stream API and come up with something like this:
IntStream.iterate(1, (x) -> 1).limit(100).toArray()

Efficient way of putting word lengths from text file into array [duplicate]

This question already has an answer here:
how to read data from file into array in Java?
(1 answer)
Closed 7 years ago.
I read a text file using scanner, removed punctuation from each line, and stored all the words in a single string array.
I'm trying to put the frequency of word lengths in an array, for example, strings with length 1 will go into another array with index 1, strings with length 2 will go into the array with index 2, to length 15 or greater, ultimately until I have all of the lengths of the word counted and put into my new array.
Is there a more efficient way of doing this instead of iterating through the array of words, and making 15 else-if statements for each word length?
Clarification: Is there any way to do this without importing any packages? It seems like the only way to do this is by iterating through it by the word length frequency array, e.g. 15 times using a double for loop or by running it through a 15 else-if statement block.
You can use the String's length as the index.
int[16] leng = {0}; // put 0 in all of the cells
String all, word;
.
.
.
leng[word.length()-1]++;
Every time you have a word with length of i it will add 1 to the location i-1 (i > 0).
The first cell (leng[0]) will contain how many words with length of 1 was.
The second cell (leng[1]) will contain how many words with length of 2 was.
.
.
.
The n cell (leng[n-1]) will contain how many words with the length of n was.
You have 16 cells (0-14 and 15+) so you can do the following:
You can do it with one condition:
if(word.length() < 15)
{
leng[word.length()-1]++;
}
else
{
leng[15]++;
}
Another way (the same but with one line):
length[(word.length()<15)(word.length()):(15)]++;
Good luck :)
Create array of lists and use string's length as index in the array. Something like that:
List<String>[] lists = new ArrayList[16];
...
lists[str.length].add(str);
I think the best way is using a HashMap like in your case HashMap<K,V> list like this example
HashMap<Integer,ArrayList> list = new HashMap<>();
list.put(lenght,new ArrayList <String>());
list.get(lenght);
More info here.

Replacing value of a two dimensional java ArrayList

I have two dimensional arrayList, and I want to replace the that is set in the program. The problem is, if i replace the value of arrayList by "ONE", it will work, if I replace it by another value bigger than one, the program enters into a loop. I am using the following syntax:
arrayList.get(index).set(index2,VALUE)
Basically this shouldn't be happening, cause I am not changing anything within the loops, or?
My Questions is WHY? and How to fix it?
the code that is (i assume) producing the problems is:
if(mark.get(index1).get(index2) == 1 && mark.get(i-1).get(j) != 1){
// Replace the value
mark.get(i-1).set(j,1);
flag = true;
}
EDIT: I removed my code, cause it gave the impression I wanted help with the code, i had posted it so that you know what I was talking about. thanks
Got what the problem was! All the initials indexes had a value of ZERO, and I had a condition that was checking if it was not ONE(assuming it will be zero anyway). if i changed it to any other value than ONE then in the next repetitions the condition would have been voided.

IndexOutOfBoundsException with Android ArrayList [duplicate]

This question already has answers here:
Java - IndexOutOfBoundsException: Index: 1, Size: 0
(1 answer)
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed last year.
I've got a very annoying problem with some code throwing an IndexOutOfBoundsException and I really cannot understand why. The logcat points to the "addTimetableItem" of the following code which ill explain more on:
if(sortedFridayTimes.size()>0){
insertDay("Friday");
for(int i=1; i<sortedFridayTimes.size()+1;i++){
addTimetableItem(sortedFridayTimes.get(i));
}
}
"sortedFridayTimes" is an ArrayList containing my own "Timetable Entry" objects which I have sorted into order already. First the size is checked to see if there are any objects and if there is then "insertDay" runs which creates a new textview for a title and adds it to the layout (This works fine..).
Inside the for loop the idea is to then add all the objects from the arraylist into the layout. Now I know that the "addTimetableItem" code works as ive tested it already, but my problem is that i cant seem to get the last object out of the arraylist. If I declare the for loop to only run for
"i<sortedFridayTimes.size()"
then the program runs fine but I don't get the last entry in the arraylist which I know exists because I've debugged and watched my variables. On adding the "+1" as shown above I now get the IndexOutOfBoundsException and I really don't know why. As I've said, I've debugged and I know that an entry exists in the arraylist where I'm trying to point to, but it just crashes. I can provide more code if needs be, but does anyone have any ideas please?
You should accept #Tim's or #Graham's answer, this is just an addendum. They're correct about your size()+1 going past the end of the array.
If you're having difficulty using indexes to properly get everything out of the list, you can also try using a for-each loop (depending on the version of the Android SDK you're using). I'm assuming sortedFridayTimes is a list of class TimetableItem since you don't specify.
So this:
if(sortedFridayTimes.size()>0){
insertDay("Friday");
for(int i=1; i<sortedFridayTimes.size()+1;i++){
addTimetableItem(sortedFridayTimes.get(i));
}
}
Becomes this:
if(!sortedFridayTimes.isEmtpy()){
insertDay("Friday");
for(TimetimeItem item : sortedFridayTimes){
addTimetableItem(item);
}
}
A little cleaner if you don't actually need to use i anywhere.
i<sortedFridayTimes.size()+1
You are looping past the last element in the array. Why the +1?
If there are N elements in the array, then the elements are from indexes 0 through to N-1.
So it should be:
for(int i=0; i<sortedFridayTimes.size(); i++) {
The last loop in your for loop runs:
sortedFridayTimes.get(sortedFridayTimes.size())
This will always be out of bounds, because the elements are zero indexed.
For example, if the array size is "5", then you cannot access index "5", because the 5 elements in the array are 0,1,2,3,4.

Categories

Resources