-1

I am trying to execute a java method solve(String s) which takes the string and returns the biggest number present in the string. (The string contains letters and numbers). Whenever I try to run the code it throws an error - java.lang.IndexOutOfBoundsException: Index: 11, Size: 11 This is my code:

    public ArrayList<Integer> getIntArray(ArrayList<String> stringArray) {
      ArrayList<Integer> result = new ArrayList<Integer>();
      for(String stringVal : stringArray) {
         result.add(Integer.parseInt(stringVal));  
      }
      return result;
   } 
   
   public int solve(String s) {
      StringBuilder str = new StringBuilder(s);
      ArrayList<String> arr = new ArrayList<String>();
      String[] strArr = s.split("");
      for(int i = 0; i < strArr.length; i++) {
         arr.add(strArr[i]);  
      }
      for(int i = 0; i < strArr.length; i++) {
         if(!Character.isLetter(i)) {
            arr.remove(i);   
         }
      }
      ArrayList<Integer> intArr = new ArrayList<Integer>();
      intArr = getIntArray(arr);
      return Collections.max(intArr);

Thanks. Any help will be appreciated.

  • Does this answer your question? [What is IndexOutOfBoundsException? How can I fix it?](https://stackoverflow.com/questions/40006317/what-is-indexoutofboundsexception-how-can-i-fix-it) – Progman Sep 19 '20 at 08:46

1 Answers1

0

Most likely the problem is in the second for loop: in the loop stop condition you are checking the length of the strArr array, while inside the loop you are removing elements from the arr list. BTW, there are several other problems with your code:

  • iterating over a list and removing elements inside the loop is not a best idea (it won't work as you would expect) You could add condition to the first loop, or, even better, use streams.
  • Character.isLetter(i) is always false, probably you meant Character.isLetter(arr[i]).
Mafor
  • 9,668
  • 2
  • 21
  • 36