1

I am getting this error when I enter Long 123456

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(Unknown Source)
at thuchanh01.Baitap05.sumDigits(Baitap05.java:17)
at thuchanh01.Baitap05.main(Baitap05.java:31)

My code: (Please note that the code is still complete and I have entered some print statements for checking)

package thuchanh01;


import java.util.Scanner;

public class Baitap05 {
private static Scanner input;
public static int sumDigits(long n)
{
    String arrayN = Long.toString(n); //conver long to string
    int len = arrayN.length(); //length of string
    Character[] array = new Character[len]; //create char array with length = length string
    int sum = 0;

    for(int i = 0; i<=len; i++)
    {
        array[i] = new Character(arrayN.charAt(i)); //assign array[i] = arrayN[i]
        sum = sum + array[i]; //result sum
    }
    return sum;

}

public static void main (String[] args)
    {
        long dayso;
        long sum = 0;
        input = new Scanner(System.in);
        System.out.println("Nhap vao day so = ");
        dayso = input.nextLong();
        sum = sumDigits(dayso);
        System.out.println("Tong can tim = " + sum);


    }

}

0

3 Answers 3

2

The valid indexes for an array range from 0 to len - 1, but your for loop attempts to use an index equal to the len.

for(int i = 0; i<=len; i++)

Change it to

for(int i = 0; i<len; i++)

to stop after the loop with i equal to len - 1.

To sum the digits, you must account for the fact that the char '2', for example, doesn't have a numerical value of 2; the Unicode (and ASCII) code is 50. In fact, all digits starting with '0' through '9' range from 48 through 57.

Subtract the char '0' from the character to get the actual numeric value, because '2' - '0' is 2.

sum = sum + array[i] - '0';
Sign up to request clarification or add additional context in comments.

2 Comments

But I am trying to calculate the total 234, which means that 2 + 3 + 4 = 9 But the result returned is 153. It is wrong in this place?
I've amended my answer; you were adding the Unicode (or ASCII) values of the digits, not the numerical value of the digits.
2

The for loop should be:

for (int i = 0; i < len; i++) {

instead of

for (int i = 0; i <= len; i++) {

Characters start at index 0 and end at index arrayN.length() - 1.

Comments

1
for(int i = 0; i<=len; i++)
{
        array[i] = new Character(arrayN.charAt(i)); //assign array[i] = arrayN[i]
        sum = sum + array[i]; //result sum
}

Change to i < len

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.