I'm trying to run my code and it says something about the exception:
java.lang.ArrayIndexOutOfBoundsException
I googled it, from what I understand it happens when I try to access an index that's negative or greater than my array length.
But I can't seem to find the problem, here's my code: http://pastebin.com/sXsBbYfh
Thanks for any helpers.
EDIT: the error message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Calculator.addOne(Calculator.java:127)
at Calculator.add(Calculator.java:88)
at Program.main(Program.java:8)
About the relevant part of the code, I have no idea, that's why i'm coming to you.
The issue would appear to be with line 86
arrResult = this.addOne(arrResult.length);
Array indexes are 0 based, so 0 - length-1 and you are passing length in and then using that to access your array on line 127
switch(arrResult[arrayIndex])
This part of code :
public int[] addOne(int arrayIndex)
124.
{
125.
switch(arrResult[arrayIndex])
126.
{
127.
case 0:
128.
arrResult[arrayIndex] = 1;
Is source of error.
Note that.
In java, arrays index range from 0 to length-1
In your code above, when method addon() is called , you are passing array length as parameter, and in code above you are trying to access array[length] which does not exist and hence the exception. Thus you may want to keep that length-1
In the following code line #86
arrResult = this.addOne(arrResult.length);
There are lot of logical errors in your code. This is just the one that throws the exception you mentioned
Related
String inputOrig = event.getMessage();
inputHist += inputOrig;
inputHist = inputHist.substring(Math.max(0, inputHist.length()-256));
The bottom line will occasionally cause and IndexOutOfBounds exception with a negative index, but I thought that shouldn't be possible because I'm taking the greater of an expression and a zero. it should be defaulting to zero shouldn't it?
edit: this is the exception
Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: -2
at java.lang.String.substring(Unknown Source) ~[?:1.8.0_171]
there's another just like it with an index of -20, and the next line just points to the method this code is in.
I'm trying to use inputHist as a history of event.getMessage() that caps at 256 characters and I thought this worked. This or at the least something similar worked before in my code but I'm not sure if I accidentally changed something or other, and if I did I can't tell what it is.
So I was correct in saying that that line was supposed to be working. The issue was with the other substring I was using in the method that I managed to completely miss. Later on in the method I am removing inputOrig from the history if it meets certain criteria, in order to prevent a feedback loop.
inputHist = inputHist.substring(0,inputHist.length()-inputOrig.length());
I'm not entirely sure how to fix it yet but that would be an entirely different question. I'll keep looking and ask it later if I can't solve it. Thank you all for your help and bearing with my mistake.
When your inputOrigin has the lenght of 0 can cause index out of bound becaue indexes are start from 0 then the last character of the string is its length -1
I think you should add -1 to your upper limit and check the different conditions again
While practising Java arrays in Eclipse, I have encountered this weird behaviour of arrays.
public class base3 {
public static void main(String[] args) {
int arr[]= new int[25];
System.out.println(arr[0]);
//System.out.println(arr[25]);
System.out.println(arr[-10]);
}
}
Output of this is:
0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -10
at base3.main(base3.java:6)
But as soon as I change the index of third sysout from -10 to -11, the sequence of output changes.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -11
at base3.main(base3.java:6)
0
So why does the output sequence changes along with array index.
This is happening due to the the output is written to different file. The output 0 is printed to standard output(fd 1) and the exception to standard error(fd 2). You could see this when you redirect standard error to /dev/null
❯ java base3 2>/dev/null
0
See how you don't get exception here. So the order here will not be predictable due to output written to different files.
The java documentation says Prints this throwable and its backtrace to the standard error stream..
I think you are looking at a race condition between standard error and standard out to print things to the console. When the exception ArrayIndexOutOfBoundsException gets thrown, it is not handled by printing to System.out but to System.err. Since both streams have to share the console resource the order in which they get access determines the order of the print statements.
The change of -10 to -11 should not influence the result. It is the time between the call to System.out.println(arr[0]); and System.out.println(arr[-10]); that influences the order of the output.
I have the most curious index problem I could imagine. I have the following innocent-looking code:
int lastIndex = givenOrder.size() - 1;
if (lastIndex >= 0 && givenOrder.get(lastIndex).equals(otherOrder)) {
givenOrder.remove(lastIndex);
}
Looks like a proper pre-check to me. (The list here is declared as List, so there is no direct access to the last element, but that is immaterial for the question anyway.) I get the following stack trace:
java.lang.IndexOutOfBoundsException: Index: 0, Size: 1
at java.util.ArrayList.rangeCheck(ArrayList.java:604) ~[na:1.7.0_17]
at java.util.ArrayList.remove(ArrayList.java:445) ~[na:1.7.0_17]
at my.code.Here:48) ~[Here.class:na]
At runtime, it’s a simple ArrayList. Now, index 0 should be quite inside the bounds!
Edit
Many people have suggested that introducing synchronization would solve the problem. I do not doubt it. But the core of my (admittedly unexpressed) question is different: How is that behaviour even possible?
Let me elaborate. We have 5 steps here:
I check the size and compute lastIndex (size is 1 here)
I even access that last element
I request removal
ArrayList checks the bounds, finding them inadequate
ArrayList constructs the exception message and throws
Strictly speaking, granularity could be even finer. Now, 50,000 times it works as expected, no concurrency issues. (Frankly, I haven’t even found any other place where that list could be modified, but the code is too large to rule that out.)
Then, one time it breaks. That’s normal for concurrency issues. However, it breaks in an entirely unexpected way. Somewhere after step 2 and before step 4, the list is emptied. I would expect an exception saying IndexOutOfBoundsException: Index: 0, Size: 0, which is bad enough. But I never saw an exception like this in the last months!
Instead, I see IndexOutOfBoundsException: Index: 0, Size: 1 which means that after step 4 but before step 5 the list gains one element. While this is possible, it seems about as unlikely as the phenomenon above. Yet, it happens each time that the error occurs! As a mathematician, I say that this is just very unprobable. But my common sense tells me that there is another issue.
Moreover, looking at the code in ArrayList, you see very short functions there that are run hundreds of times, and no volatile variable anywhere. That means that I would very much expect the hotspot compiler to have elided the function calls, making the critical section much smaller; and the elided the double access to the size variable, making the observed behaviour impossible. Clearly, this isn’t happening.
So, my question is why this can happen at all and why it happens in this weird way. Suggesting synchronization is not an answer to the question (it may be a solution to the problem, but that is a different matter).
So I have checked the source code for ArrayList implementation of rangeCheck - method that throws exception and this is what I have found:
private void rangeCheck(int paramInt) //given index
{
if (paramInt < this.size) // compare param with list size
return;
throw new IndexOutOfBoundsException(outOfBoundsMsg(paramInt)); // here we have exception
}
and relevant outOfBoundsMsg method
private String outOfBoundsMsg(int paramInt)
{
return "Index: " + paramInt + ", Size: " + this.size; /// OOOoo we are reading size again!
}
So as you can probably see, size (this.size) of list is accessed 2 times. First time it is read to check condition and the condition is not fullfilled, so the message is build for the exception. While creating message for the exception, only paramInt is persistent between calls, but size of list is read second time. And here we have our culprit.
In real, you should get Message : Index:0 Size:0, but the size value used for checking is not locally stored (microoptimalization). So between these 2 reads of this.size list has been changed.
That is why message is missleading.
Conclussion:
Such situation is possible in hightly concurrent environement, and can be very hard to reproduce. To solve that problem use synchronized version of ArrayList (like #JordiCastillia suggested). This solution can have impact on performance as every operation (add/remove and probably get) will be synchronized. Other solution would be to put your code into synchronized block, but this will only synchronized your calls in this piece of code, and the problem can still occure in the future, as different parts of the system can still access whole object async.
This is most likely a concurrency issue.
The size gets somehow modified before/after you tried to access the index.
Use Collections.synchronizedList().
Tested in a simple main it works:
List<String> givenOrder = new ArrayList<>();
String otherOrder = "null";
givenOrder.add(otherOrder);
int lastIndex = givenOrder.size() - 1;
if (lastIndex >= 0 && givenOrder.get(lastIndex).equals(otherOrder)) {
System.out.println("remove");
givenOrder.remove(lastIndex);
}
Are you on a thread-safe process? Your List is modified by some other thread or process.
I am currently using nested for loops in a 2D array of size 4,2.
When I run my program, I get index out of bounds Exception on the following line
else if (state[i][j+1] != null
&& state[i][j].getFlash() <= state[i][j].getCycleLength()
&& state[i][j+1].getCycleLength() == state[i][j].getCycleLength()){
}
It says the index out of bounds is 2. I would understand the error if I wasn't checking to see if [i][j+1] wasn't null, but I don't understand the exception with the check? I tried moving around the !null check but the program still fails on this line.
Any help would be greatly appreciated.
Stack trace:
Exception in thread "Timer-0" java.lang.ArrayIndexOutOfBoundsException: 2
at NatComp.data$1.run(data.java:67)
at java.util.TimerThread.mainLoop(Timer.java:512)
at java.util.TimerThread.run(Timer.java:462)
Just checking for state[i][j+1] != null prevents NullPointerException, but it does not prevents the code from raising an IndexOutOfBoundsException.
For checking the IndexOutOfBounds, you need to check your indices against the maximum allowable index. There is not point in relying on checking the elements with null. You won't even be able to access the elements, if the index is out of bounds, so the null check might not even be checked.
Also, if you have so many conditions in your if, its better to separate them in nested if, with the outer if checking for IndexOutOfBounds, and inner if doing the actual condition check. That would be more readable.
For e.g., if you have an array declared as new int[3], then before accessing an index, you can add a check for: -
if (index < 3) {
// you can now access `array[index]`, as it is safe now
// Also, you can add a check for `NPE` here.
}
That's because your indices are 0-based. So maximum accessible index is max - 1, where max is the size of your array.
You can adapt the same logic in your array of array.
It seems pretty clear from your description that j==1 when you get the exception. When that happens, state[i][j+1] would throw an ArrayIndexOutOfBoundsException rather than evaluate to null as you seem to expect.
The only value of j for which your code won't throw an ArrayIndexOutOfBoundsException is zero, so you might want to check for that instead of checking for null.
I have a strange problem which I can't fix:
A field:
private boolean[][][] gaps;
Constructor (1st line):
gaps = new boolean[NOBARRICADES][WIDTH][HEIGHT];
Constructor (2nd line):
for (int i = 0; i < NOBARRICADES; i++) {
Java throws an error for the 2nd line, saying:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
Does it have anything to do with Java syntax (the mistake is in these lines of code) or I should look for the problem somewhere else?
You're probably misreading the error output. Your second line does not even access the array - make sure that it's not the first line of the body of the for-loop that throws the exception. Also, make sure that you use i only to index the first dimension of your array.
sometimes the java compiler is off by a line or two. You may check the lines of code around the line that it says the error is on and see if you see anything.
Sorry, but you really don't want to do that.
Multidimensional arrays are never worth the confusion they cause--they have no positive value at all (with the POSSIBLE exception of a clear, obvious x,y array).
I suggest you try starting with either a list of two-dimensional arrays or a two-dimensional array of objects where each object contains a list.