• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Why do i get this run time eroor... plz help

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
My program is like this...

public class Propogate {

String reverse(String val) throws Exception{

String reverseStr ="";
System.out.println(val);
if(val.length()== 0){
throw new Exception();
}
else{

for(int i = val.length(); i>0; --i){
reverseStr = reverseStr + val.charAt(i);
}
val = reverseStr;
}
return val;

}
public static void main(String[] args) {

Propogate eh = new Propogate();
try{
System.out.println(eh.reverse("java"));
}catch(Exception e){
System.out.println(e);

}


}
}

i get a ru time error telling

java.lang.StringIndexOutOfBoundsException: String index out of range: 4
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The first index in a String is position 0. So the last position is not the length of the String, but one less. You are trying to access the position in the String indicated by its length.
 
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
for(int i = val.length(); i>0; --i){
reverseStr = reverseStr + val.charAt(i);
}

val.length()=4;

val.charAt(4); ...Its not there so run-time exception occur

...this will work.........
for(int i = val.length()-1; i>=0; --i){
reverseStr = reverseStr + val.charAt(i);
}
 
Anish Nagraj
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1. i want to know exactly when the pre-increment of i works out and the value of i becomes 2 in the program i specified.

2. i also want what difference does a pre-decrement and post-decrement in this program makes... hope it makes no difference... let me know the exact description...
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic