简体   繁体   中英

How do I print the total or sum of all the digits in an array in java?

Im trying to determine whether the number is odd or even, the length of the input and the sum of all the digits in the input.

Heres my attempt:

public static int statNum(int input) {
    if(input % 2 == 0) {
        System.out.println("The number is even");
    } else {
        System.out.println("The number is odd");
    }

    System.out.println(Integer.toString(input).length());

    String number = String.valueOf(input);
    char [] values = number.toCharArray();

    int sum = 0;
    for (int i = 0; i < values.length; i++) {
        sum = sum + values[i];
    }
    System.out.println("The sum of this number is: " + sum);

    return input;
}

If i input 1 the sum is equal to 49, if I input 1234 the input is equal to 202. What am I doing wrong?

You are adding char values ie adding the ASCII value of the char to the sum, You should parse them to int before adding

Do this

sum = sum + Integer.parseInt(Character.toString(values[i]));

or as @ZouZou suggested, can use

sum = sum + Character.getNumericValue(values[i]);

你需要减去 char'0' ,所以你只是将数值加到零以上,而不是添加char本身的值(这是它的ascii字符值):

sum = sum + values[i] - '0';

Following is a code to find sum of digits of a number & length of number :

int sum=0;
int length=0;
while(input!=0)
{
    sum+=input%10;
    input/=10;
    length++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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