1

I am getting a java.lang.StringIndexOutOfBoundsException while running this code. How do I fix this?

import java.util.Scanner;

class C {
    static int Occurence = 0;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        StringBuilder sb = new StringBuilder();
        System.out.println(sb.deleteCharAt(3));
        for (int i = str.length() - 1; i > 0; i--) {
            Occurence = 1;
            for (int j = i - 1; j > 0; j--) {
                if (str.charAt(i) == str.charAt(j)) {
                    Occurence++;
                    sb.deleteCharAt(j);
                }
            }
            System.out.println(str.charAt(i) + " repeated " + Occurence);
        }
    }
}
pushkin
  • 9,575
  • 15
  • 51
  • 95
  • After `StringBuilder sb = new StringBuilder()` add this code piece `sb.append(str)` or simply `StringBuilder sb = new StringBuilder(str)` – Yasin May 06 '18 at 17:45

1 Answers1

0
// empty, current size 0    
StringBuilder sb = new StringBuilder();

// StringIndexOutOfBoundException bcoz current size is 0, and you are accessing index 3.
System.out.println(sb.deleteCharAt(3));
Hemant Patel
  • 3,160
  • 1
  • 20
  • 29