-1

I can't seem to find how is the array overflowing. Everything seems to be fine.

class sumofnum  {

static int calculate_sum(String num)    {

    int len, sum = 0, i;

    len = num.length();

    int[] arr = new int[len - 1];

    // fill in array.
    for(i = 0; i < len; i++)
        arr[i] = Character.getNumericValue(num.charAt(i));

    // calculate sum.
    for(i = 0; i < len; i++)
        sum += arr[i];

    return sum;

} // method calculate_sum ends.

I used the above method to try to calculate sum of digits.

Actual output :

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    at sumofnum.calculate_sum(sumofnum.java:18)
    at sumofnum.main(sumofnum.java:40)
lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
Chinmay Ghule
  • 91
  • 1
  • 6
  • What are you passing as `num`? – GBlodgett Apr 25 '19 at 19:20
  • This is a program for calculating sum of digits of a number. The variable num contains the number in String form. – Chinmay Ghule Apr 26 '19 at 14:24
  • Possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – GBlodgett Apr 26 '19 at 15:30

3 Answers3

1

Substitute int[] arr = new int[len - 1]; for int[] arr = new int[len];.

You need to create the array where you're going to store the string characters the same length as the string (numbers of characters).

Otherwise you will get the mentioned exception in this line in the last iteration:

arr[i] = Character.getNumericValue(num.charAt(i));
lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
1

The problem is in this line:

int[] arr = new int[len - 1];

While the index goes from 0 to len-1, the size is len. Use instead:

int[] arr = new int[len];
priyank-sriv
  • 1,094
  • 6
  • 12
0

the error is at

int[] arr = new int[len - 1];

the array created is of size less then the length of the string, thats why at last iteration it gives index out of bound exception

Also you can use a single loop to do both adding and getting the integer of character avoiding array itself by doing

   for(i = 0; i < len; i++){
    sum+= Character.getNumericValue(num.charAt(i));
}