write a java program that prompts the user to input and integer and then ouputs both the individual digits of the number and the sum of the digits.
This is what I have but it is not working when I input a negative number. Why? Need help!

import java.util.*;

public class sumDigits {
    public static void main(String[] args) {

        int aDigit, aNum, theSum=0;
        String aStringNum;
        char digitAt;

        Scanner console = new Scanner(System.in);

        System.out.println("Please enter an integer ");
        aNum = console.nextInt();

        aStringNum = String.valueOf(aNum);

        for (int count=0; count < aStringNum.length(); count++) {

            digitAt = aStringNum.charAt(count);

            aDigit = Character.getNumericValue(digitAt);

            theSum += aDigit;

            System.out.print(aDigit + " ");
        }

        System.out.println("The sum is:  " + theSum);
    }
}

Recommended Answers

All 6 Replies

And what it is supposed to be for a negative value? Also, it wouldn't work because the returned string has a "-" sign in front. If you want to sum only, then use Math.abs() on your "aNum" before you use the String.valueOf()???

This is what the program is currently outputting...
Please enter a positive integer
1234
1 2 3 4 The sum is: 10

BUT WHEN I ENTER A NEGATIVE NUMBER LIKE...

Please enter a positive integer
-2345
-1 2 3 4 5 The sum is: 13

as you can see the program added the number 1 digit and I can't see why. The output should read...

2 3 4 5 The sum is: 14

Referred to my post, you could simply force it to be positive by using Math.abs(aNum) before you convert the value to string.

I did use Math.abs(aNum) before aStringNum = String.valueOf(aNum);
but still getting the same results when i want to input a negative digit.
I am getting the same output when I enter

-2345

-1 2 3 4 5 The sum is: 13

it should output it like this

2 3 4 5 The sum is: 14

You need to reassign to aNum.

aNum = Math.abs(aNum);

If not, you could just do

aStringNum = String.valueOf(Math.abs(aNum));

Thanks! All is well.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.