-1

I tried to code method that gives first reccuring char but when the string doesn't have any I get this error:

java.lang.ArrayIndexOutOfBoundsException: 3

Code:

static char firstReccuring(char str[]){
    HashSet<Character> map = new HashSet<>();

    for(int i=0; i<=str.length; i++ ) {
        char ch = str[i];
        if(map.contains(ch)) {
            return ch;
        }else {
            map.add(ch);
        }
    }

    return '0';
}

public static void main(String[] args) {
    String str = "abc";
    char[] arr = str.toCharArray();
    System.out.println(firstReccuring(arr));

}
khelwood
  • 55,782
  • 14
  • 81
  • 108
Asek90
  • 1

2 Answers2

1

Turn i<=str.length into i<str.length Your String only has three characters, meaning the biggest index in the array will be 2

Stultuske
  • 9,296
  • 1
  • 25
  • 37
1
for(int i=0; i<=str.length; i++ ) {`

remove the equal because if string have length of n , max accessible index is n-1

nissim abehcera
  • 821
  • 6
  • 7