Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

ArrayIndexOutOfBounds Exception  RSS feed

 
sai prasanna
Ranch Hand
Posts: 167
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all,

public class StringReverse{
public static void main(String sai[]){

String[] result = "sai ram".split("\\s");
System.out.println(result.length);
int x;
for (x=0; x<result.length; x++)
// System.out.println("x = "+x);
System.out.println("result = "+result[x]);


}
}


when iam removing comments it is throwing an exception as follows

when iam removing comments it is throwing an exception as follows

2
0
1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at StringReverse.main(StringReverse.java:9)

why not the following output is not printed along with the above output

result = sai
result = ram

please explain
Thanks in advance
saiprasanna
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you remove the comments, you actually move the next statement out of the loop... I think you meant to do this.



Henry
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My guess is that when you commented the line, you did not but braces around it and the next line.

Remember that when you don't have braces following a structure like if, while, or for, then the next line is the body of the loop.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!