Sunday, April 8, 2018

[Java][Resolved] Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0

Error message

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
    at java.lang.String.charAt(String.java:658)
    at intro.Example.go(Example.java:14)
    at intro.Example.main(Example.java:6)
Java Result: 1

Source Code

class Example{
    public static void main(String[] args){
        int result = new Example().go("!!day--yaz!!");
        System.out.println(result);
    }
    public int go(String str) {      
      int amount = 0;
      String[] parts =str.split("\\P{Alpha}+");
        for (String part : parts) {
            System.out.println(part.charAt(part.length()-1));
        }
      return amount;
    }
}

Problem 

Be ware is your charAt() method applied on an empty String. In this case, parts is a String array with 3 items : "","day" and "yaz". First item is empty. I add a checking check is String item empty before using charAt() method.

Corrected code

class Example{
  
    public static void main(String[] args){
        int result = new Example().go("!!day--yaz!!");
        System.out.println(result);
    }
   
    public int go(String str) {      
      int amount = 0;
      String[] parts =str.split("\\P{Alpha}+");
        for (String part : parts) {
            if(part.length()>0){
            System.out.println(part.charAt(part.length()-1));
            }
        }
      return amount;
    }

}

Reference

https://stackoverflow.com/questions/9220281/java-lang-stringindexoutofboundsexception-string-index-out-of-range

No comments :

Post a Comment