Index-out-of-bound exception in java - java

Exception messages:
Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
Following is the code I am using to highlight specific words in JTextPane. My objective is to create a simple syntax highlighting editor, I have searched thoroughly about it and have found many interesting solutions but I wanted to write my own code for it and now I am stuck on an IndexOutOfBoundsException.
My editor gives this exception whenever third key is pressed , meaning whenever 2 letters are written in the JTextPane.
My apologies if the code is not easily understandable, I am new at learning conventions.
I know this is a very trivial question but any sort of help would be considerable.
Thank you :)
[Update] The first part of the code works on the jTextPane2KeyTyped event
String[] words = new String[] {"if","else","for"};
//words is the list for words to change color
StyledDocument doc = jTextPane2.getStyledDocument();
Style style=doc.addStyle("Red_Colour", null);
StyleConstants.setForeground(style, Color.RED);
StyleConstants.setForeground(common,Color.BLACK);
String temp = jTextPane2.getText();
//temp holds the string value of the text present in the jTextPane2
int check=0;
for(int i=0;i<temp.length();i++){
for(int j=0;j<words.length;j++){
if(charLeft(temp,words,i,j)){
if(temp.length()>=words[j].length())
for(int k=0;k<words[j].length();k++){
if(temp.charAt(i+k)==words[j].charAt(k))check++;
}
//else{break;}
if(check==words[j].length()){
doc.setCharacterAttributes(i,words[j].length(),style, false);
}
}
}
}
Following is the code for the method called(i.e. charLeft())
public Boolean charLeft(String temp,String[] words,int i,int j){
temp= temp.substring(i, temp.length());
if(temp.length()<words[j].length())return true;
else return false;
}
TrackBack for the exceptions
Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.lang.String.charAt(String.java:658)
at NewJFrame.jTextPane2KeyTyped(NewJFrame.java:164)
at NewJFrame.access$000(NewJFrame.java:24)
at NewJFrame$1.keyTyped(NewJFrame.java:59)
at java.awt.Component.processKeyEvent(Component.java:6460)
at javax.swing.JComponent.processKeyEvent(JComponent.java:2828)
at java.awt.Component.processEvent(Component.java:6282)
...
Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.lang.String.charAt(String.java:658)
at NewJFrame.jTextPane2KeyTyped(NewJFrame.java:164)
at NewJFrame.access$000(NewJFrame.java:24)
at NewJFrame$1.keyTyped(NewJFrame.java:59)
at java.awt.Component.processKeyEvent(Component.java:6460)
at javax.swing.JComponent.processKeyEvent(JComponent.java:2828)
...

You're actually incrementing j in the third loop as well, instead of k:
if(temp.length()>=words[j].length())for(int k=0;k<words[j].length();j++)
A spontaneous guess would be that you should change it to the following, to avoid exceeding the max length:
if(temp.length()>=words[j].length())for(int k=0;k<words[j].length();k++)

I think that this line might be your problem (This is line 3 of the second code block you posted):
if(temp.length()>=words[j].length())for(int k=0;k<words[j].length();j++){if(temp.charAt(i+k)==words[j].charAt(k))check++;}
You actually increment j instead of k here:
for(int k=0;k<words[j].length();j++)
And because j corresponds to words.length (which is 3) when you type the third character it tries to reference words[3] which does not exist. I would suggest changing it to:
for(int k=0;k<words[j].length();k++)
Hope that helps.
Edit:
Now I am thinking that instead of saying:
if(temp.charAt(i+k)==words[j].charAt(k))check++;
You might want to say:
if(temp.charAt(i)==words[j].charAt(k))check++;

Fixed! The problem was that I was not changing the value of count back to zero. Other problem was in the conditional operator in charLeft() , which was
if(temp.length()<words[j].length())return true;
Corrected condition is
if(temp.length()>=words[j].length())return true;

Related

Java Exception: java.lang.StringIndexOutOfBoundsException

I have some problems with the code every time I try to compile the exception java.lang.StringIndexOutOfBoundsException appears. Here is the code with the problem I really don't know what I have done wrong. In the code I try to split a string using some conditions, the string represent a polynomial.
int[] coef1= new int[20];
for(i=0;i<polinom.length()+1;i++){
if(polinom.charAt(i)=='+' )
c=polinom.charAt(i+1);
else{
if(polinom.charAt(i)=='^'){
v=Integer.parseInt(Character.toString(polinom.charAt(i+1)));
coef1[v]=Integer.parseInt(Character.toString(c));
System.out.print(coef1[v]);
}
}
}
for(i=0;i<polinom.length()+1;i++){
if(polinom.charAt(i)=='-' )
c=polinom.charAt(i+1);
else{
if(polinom.charAt(i)=='^'){
v=Integer.parseInt(Character.toString(polinom.charAt(i+1)));
coef1[v]=-Integer.parseInt(Character.toString(c));
System.out.print(coef1[v]);
}
}
}
The exception is here if(polinom.charAt(i)=='+' )
Just replace all your
for(i=0;i<polinom.length()+1;i++){
with
for(i=0;i<polinom.length()-1;i++){
As indices are 0-based and you use polinom.charAt(i+1), i+1 should never be equal (nor greater) than polinom.length.
Or if you want ot be able to test until the last character of you string (for other processing), you can ensure that polinom.charAt(i+1) gets never triggered if i == polinom.length() - 1, just add a test before processing your stuff:
for(i=0;i<polinom.length();i++){ // not using -1, looping to the end of the string
if(polinom.charAt(i)=='+' && i < polinom.length() - 1) // checking that no exception will be thrown
c=polinom.charAt(i+1);
else{
if(polinom.charAt(i)=='^' && i < polinom.length() - 1){ // same
v=Integer.parseInt(Character.toString(polinom.charAt(i+1)));
coef1[v]=-Integer.parseInt(Character.toString(c));
System.out.print(coef1[v]);
}
}
}
In the second line here you are using
for(i=0;i<polinom.length()+1;i++){
That +1 should be -1.
I suppose the variable polinom is a String.
Your're looping beyond the end of the string:
for(i=0;i<polinom.length()+1;i++)
It should be
for(i=0;i<polinom.length()-1;i++)

Strange(?) out - of - bound with Stringuilder on array

There last 2 days I am 100% brain dead and cant find where the error is... Can anyone give me a tip >>
for(String inputString : word)
{
StringBuilder sb = new StringBuilder(inputString);
if(inputString.charAt(inputString.length()-1) == ']')
{
sb.deleteCharAt(inputString.length());
}
else if(inputString.charAt(0) == '[')
{
sb.deleteCharAt(0);
}
breaker.add(sb.toString());
}
It was suppose to be a simple function to remove the [ ] characters from a string but everytime I run it I get
Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
But only on the third or fourth pass never the first or second.
Confused.
sb.deleteCharAt(inputString.length());
should be
sb.deleteCharAt(inputString.length() - 1);
Because you want to remove the last character (you did it correctly in the test!)
You're deleting the last char at the StringBuilder's length, rather than length - 1.
StringBuilder, not unlike all String and array representations in Java, is 0-indexed.
Use the following idiom instead:
sb.deleteCharAt(sb.length() - 1);
The reason why the StringIndexOutOfBoundsException is only thrown arbitrarily in your execution is likely because of the condition checking for the ] character, which may not always hold true (hence the offending code would not execute).

How to check the end of args array?

I am writing a parser program in Scala that should read input using "args" and pars it. It doesn't matter I use:
while(!args.isEmpty){
if (Files.exists(Paths.get(args(j)))){
Statement=Statement.concat(inputXml)
Statement=Statement.concat(" ")
println(j)
}
else{
Statement=Statement.concat(args(j))
Statement=Statement.concat(" ")
println(j)
}
j=j+1
}
or
while(args.length !=0) {
if (Files.exists(Paths.get(args(j)))){
Statement=Statement.concat(inputXml)
Statement=Statement.concat(" ")
println(j)
}
else{
Statement=Statement.concat(args(j))
Statement=Statement.concat(" ")
println(j)
}
j=j+1
}
The program gives me run time exception of array index out of bound! sending 2 values as input:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
what should I do? I am confused!
Your exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
Is because you are not breaking the while loop; the args parameter never change it's size, so your while will go forever util j exceed the size of args.
Maybe you could try:
int i = 0
while (i < args.length){
// some code here
i++;
}
or
for(int i = 0; i < args.length; i++){
// some code here
}
If you want to iterate through all the array
From what you describe, you need to iterate through your array while your index is lower than the maximum array size. If you merely compare args.length value, the loop condition will continue to evaluate to a truth value infinitely, since args.length will always be different than 0 (if not changed).
You need something along the lines of:
for(i <- 0 until array.length){
...
You can find extra information on accessing and iterating over arrays here and here
Consider iterating over args without using indexed references (the source of out-of-bounds error),
for ( arg <- args ) yield {
if (Files.exists(Paths.get(arg))) xmlFile
else ""
}.mkString(" ")
This for comprehension yields a collection of String which is converted to a space-separated string with mkString.

String index out of bounds? Where?

This is my code for finding the no. of vowels in a string:
{
String inyo=inpeo.getText().toLowerCase();
System.out.println(inyo); // Just checking for an empty string
int vowcount=0;
for(int i=0;i<=inyo.length();i++)
{
char rol=inyo.charAt(i);
if(rol=='o'||'u'==rol||rol=='a'||rol=='e'||rol=='i')
{
vowcount=vowcount+1;
System.out.println(vowcount);
}
numout.setText(""+vowcount);
}
}
Now, nothing is wrong with the output here-it finds the exact no. of vowels as I intended. But it gives me this error:
Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.charAt(String.java:646)
at WordCheck.jButton2ActionPerformed(WordCheck.java:147)
// Extra errors removed as they're irrelevant to my issue
As a result, there is no way of reusing the program other than closing and restarting it. when the output is coming out as desired, why am I getting this error? I don't get any empty Strings, either.
The last iteration of the for loop is causing the exception (when i == inyo.length()). Simply replace it with:
for(int i=0; i<inyo.length(); i++)
i<=inyo.length() here. The String index starts from 0. The length count starts from one. So, the last index of a String is 4 when its length is 5.
It should be
i<inyo.length()
Your for loop is going one too far, this
for(int i=0;i<=inyo.length();i++)
should be
for(int i=0;i<inyo.length();i++)
Note that when i == invo.length() it's passed the end of the array, because Java starts indexing with 0.
The for loop should be
for(int i=0; i<inyo.length(); i++)
Presently when it goes to the last iteration the index of the string is 4 whereas inyo.length() is 5. Hence it results in out of bounds.

Java, check is substring of string doesn't "exist"

I have a while loop that is supposed to seperate a word into individual letters... It works but then when ever i try to check if a substring that does not exist is null it throws exceptions...
private static void seperateWord(String word) {
boolean running = true;
int count = 0;
while (running) {
if (word.substring(count, count + 1).equals("null")) {
running = false;
return;
} else {
letter[count] = word.substring(count, count + 1);
System.out.println(letter[count]);
count++;
}
}
}
It does output all the letters correctly until it gets to the end of the string and has nothing left to read... as in it just does not exist. It throws this exception...
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.substring(Unknown Source)
at Class.seperateWord(Class.java:33)
at Class.main(Class.java:13)
Line 33 is :: if (input.substring(count, count + 1).equals("null")) {
Line 13 is just where I call the method.
The text I entered is "abc"
Thanks in advance for any help!
You're trying to get the substring going from index 3 to index 4 on a string which has only 3 characters. This is why you get an exception.
Moreover, input.substring(count, count + 1).equals("null") will obviously never be true. How could a string of 1 character ever be equal to the string "null", which has 4 characters?
Read the API doc of the String class. It has a length() method which returns the length of the string, and that you should use to stop your loop. It also has a charAt() method which returns the character at a given index.

Categories