Java Substring: Why is this going out of bounds sometimes? - java

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

Related

Parsing with Scanner findWithinHorizon issue

in a project I'm working right now, I need to parse escape sequences with the Scanner class (using Java in Linux). To include, for instance, the two END keys in the keyboard, I initially wrote the following code:
if(sc.findWithinHorizon("(\\G\\e\\[4~)?",0).length() > 0 || sc.findWithinHorizon("(\\G\\eOF)?",0).length() > 0 ) {
System.out.print("END"); //To see if it works
With that code, I don't get any output (the terminal just freezes). After seeing that, I separated the two condition in two different if's:
if(sc.findWithinHorizon("(\\G\\e\\[4~)?",0).length() > 0)
System.out.print("END");
else if(sc.findWithinHorizon("(\\G\\eOF)?",0).length() > 0 )
System.out.print("END");
Then it works. Does anybody know why it doesn't work with the OR operator?
Thanks in advance.
You'll want to capture what findwithinhorizon parses into a String then do your comparisons. What you're doing in the first if statement is parsing sc twice. Once doing a comparison for something then the second time doing a different comparison on a different part of the text.
I doubt this is the behavior you wanted. when you set horizon to 0 it's going to look at what is the current position then increment the position by one, so your second call is looking at a different index. If you truly have reached the end of the file I would believe this would cause some odd behavior and explain why it hangs.

Best way to find character at specific index in a compressed String

I know that we can do this by following ways
StringBuilder
Use substring
But i am looking a way where i have a compressed String say a5b4c2 etc which means a is 5 times b is 4 times etc so String is actually aaaaabbbbcc something like that.
So char at index 2 should return a and char at index 6 should return b.
What can be the best approach for this?
My question is more about what is the best approach to decompress String ?
My question is more about handling this compressed string rather than finding the character at specific index.
Decompress the string until you get the index you want to know. Or you could decompress the whole string and cache it.
What can be the best approach for this?
Without any more specific requirements, I believe the best approach is the simplest approach you can think of.
I would, parse each pair of the letter and the number in turn, reduce the index by that number and if the remaining index is < 0 you have the letter you want.
Check what index you are searching for, and start adding up the numbers of characters. Every time you add, check if the index falls within the previous interval and the current one. If it does, you've found what your character is, otherwise add again.
For example, the workflow given your string a5b4c2, if you want the character at index 7, could be like this:
current position: 0
index we are looking for: 7
add first character's count: 0+5 = 5
does 7 fall within 0 and 5? no, add again
current position: 5
add second character's count: 5+4 = 9
does 7 fall within 5 and 9? yes, so our character must be 'b'.
I'm not sure if this is more efficient or faster than decompressing the string and just using charAt() or something, it's just a different way of approaching it.
EDIT: Since the question is more about how to decompress the string, you could use a StringBuilder and use a for loop to append the correct number of the character to your string... sounds like the simplest way to me.

Java - java.lang.ArrayIndexOutOfBoundsException

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

While loop doesn't work in Android but works in a normal Java class?

Hi I am having a problem with my while loop in the getAmatch() function
It doesn't enter the while loop in android but enters in a normal Java class.
All I can say off the top of my head without a bit more information is watch your case sensitivity on both input and patterns, and your while loop is a good piece of evidence; your matcher.find() is simply not finding a match. As it states in the documentation:
Parameters:
start: The index in the input at which
the find operation is to begin. If
this is less than the start of the
region, it is automatically adjusted
to that value. If it is beyond the end
of the region, the method will fail.
Returns:
true if (and only if)** a match has been found.

Multi-Dimensional Array and ArrayIndexOutOfBoundsException

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.

Categories