0
public class demo {
    
    public void countCharacter(char[] ch) {
        
        String str=new String(ch);
        
        int count = 0,len=0;
        
        do {
            char[] charToLoop = str.toCharArray();
            
            len = charToLoop.length ;
            count = 0;
            
            for(int i=0;i < len;i++) {
                
                if(charToLoop[0] == charToLoop[i]) {
                    count++;
                }
            }
                if(count!=0) {
                    System.out.println(charToLoop[0] + " " + count);
                }
                
                str = str.replace(""+charToLoop[0], "");

        } while (len != 0);

    }
    
    public static void main(String[] args) {
        
        
        String s;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter your String");
        
        s = sc.nextLine();
        
        char[] ch = s.toCharArray();
        
        demo l4 = new demo();
        
        l4.countCharacter(ch);
    
    }
  
}

Output:

Enter your String
sana
s 1
a 2
n 1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0

Without using try/catch, how can I solve this exception?

Tom
  • 16,842
  • 17
  • 45
  • 54
Sanjeevi R
  • 21
  • 1
  • 1
  • Don't access array indexes that don't exist. When you remove chars from a String, then the char array will become empty, so `charToLoop[0]` won't work anymore. – Tom Feb 26 '21 at 19:16
  • When len becomes 0, your code continues until the end of the while loop and hence the exception. Execute e. g. a break immediately when len becomes 0. – Jörg Feb 26 '21 at 19:23

1 Answers1

0

You can fix the problem by recalculating the length of the string at the right time:

        } while (str.length() > 0);

Explanation:

The ArrayIndexOutOfBounds is because you enter the loop one time too many; the 'len' you're comparing against is no longer the length of the string after str.replace reduced it by at least one.

Putting while (len > 1 ) fixes the problem for input 'sana', but will still fail for 'snaa', because str.replace replaces ALL occurences of the first argument; so both 'a'-characters get removed in one go, and with input 'snaa' that reduces the length of the string from 2 to 0 in one pass through the loop.

The validation in the while-statement is using 'stale' data: 'len' no longer holds the length of the string after str.replace has done its job; so calculate it again when doing the validation: while (str.length() > 0).

Side-notes:

  • do { ... } while() is way more difficult than while(){ ... }. In your case: your example will still fail with empty input (user just hits enter). But while(str.length() > 0) { ... } will automatically catch that, because it won't allow the first pass through the loop-body. I honestly don't think there's any sensible use for do-while.

  • of course this is not an exercise in performance, but consider using only the char[] ch argument, without creating a String out of it for achieving the same goal. str = str.replace(...) is a very heavy solution.

Bart Robeyns
  • 571
  • 4
  • 14