简体   繁体   English

计算数字位数总和时发生数组溢出

[英]Array overflow while calculating sum of digits of a number

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)

Substitute int[] arr = new int[len - 1]; 替换为int[] arr = new int[len - 1]; for int[] arr = new int[ len ]; 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));

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 . 当索引从0到len-1 ,大小为len Use instead: 改用:

int[] arr = new int[len];

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));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM