0

So Im trying to make a program that counts how many numbers and letters a string has and save the numbers in an array of ints and the letters in an array of chars but it keeps throwing the out of bounce error.

public static void main(String[] args) {


        Scanner k = new Scanner(System.in);

        System.out.println("Enter a string");
        String s = k.nextLine();

        int spaceCount = 0;
        int[] intarray;
        char[] charArray;
        int numCount = 0;
        int letterCount = 0;
        for (int i = 0; i < s.length(); i++) {


            if (Character.toString(s.charAt(i)).matches("[0-9]")) {


                numCount++;

            } else if (Character.toString(s.charAt(i)).matches("[a-zA-Z]")) {

                letterCount++;


            }else {

                continue;
            }
        }

        System.out.println(numCount);
        System.out.println(letterCount);

        intarray = new int[numCount];
        charArray = new char[letterCount];



            for (int i = 0; i <s.length(); i++) {


                if (Character.toString(s.charAt(i)).matches("[0-9]")) {

                    intarray[i] = s.charAt(i);
                    continue;
                }else if (Character.toString(s.charAt(i)).matches("[a-zA-Z]")){


                    charArray[i] = s.charAt(i);
                    continue;




                }




            }

            for (int i =0;i<intarray.length;i++){

                System.out.println(intarray[i]);
            }

            for (int i=0;i<charArray.length;i++){

                System.out.println(charArray[i]);
            }
}
}
Srikanth A
  • 2,428
  • 4
  • 13
  • 28
george129
  • 35
  • 3
  • 1
    You can't use `intarray[i]` and `charArray[i]` in your second loop. You need separate indices for those arrays (to count the current digit or char respectively). – Elliott Frisch Mar 05 '17 at 01:26
  • 1
    Before I read any further, a quick note: are you sure you're getting an ArrayOutOf**Bounce error**? – domsson Mar 05 '17 at 01:26
  • This is what Im getting – george129 Mar 05 '17 at 01:35
  • Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: – george129 Mar 05 '17 at 01:35
  • He's probably talking about something like this :-) - https://www.youtube.com/watch?v=yx62tt1Ci4U Hint George: "bounce" and "bounds" are different words in English. They don't even *sound* the same if you pronounce them correctly. – Stephen C Mar 05 '17 at 01:39

0 Answers0