0

I want to read a number as a String, and split its characters to an integer array, and find the sum of it's digits by looping through that integers array.

This is my code so far:

public static void main(String[] args) {
    Scanner S = new Scanner(System.in);
    String Number = S.next();
    int counterEnd = Number.length();
    int sum = 0 ;

    for ( int i = 0 ; i < counterEnd ; i++) {
         sum += sum + (Number.charAt(i));
    }

    System.out.println(sum);
}

Unfortunately, this code prints the sum of ASCII not the digits.

0

4 Answers 4

5

You can subtract the '0' character (i.e. '1' - '0' is 49 - 48 = 1):

sum += Number.charAt(i) - '0';
Sign up to request clarification or add additional context in comments.

1 Comment

This technique is the classic approach, but I'm not a huge fan of relying on the implicit ordering of a character table. It just feels a bit hacky, or at least below the level of abstraction that an OO language like Java should be dealing with. This will work though, since the ASCII table will probably never get redefined.
4

You could, has @August suggested, substract the character '0' to obtain the numeric value of the character (I find this approach kind of hackish). Or you can use Character.getNumericValue to achieve this:

sum += Character.getNumericValue(Number.charAt(i)); //note it's sum += theDigit; not sum += sum + theDigit

You might also want to look at the enhanced for loop, as you basically don't need the index here:

for(char c : Number.toCharArray()) {
    sum += Character.getNumericValue(c);
}

As of Java 8 you could also do it like this:

int sum = Number.chars().map(Character::getNumericValue).sum();

It basically gets a Stream of the characters in the String, map each character to its corresponding numeric value and sum them.

Comments

0
sum+= Integer.parseInt(String.valueOf(Number.charAt(i)));

Comments

0

You can do it like this:

   public static void main(String[] args) {
     Scanner S = new Scanner(System.in);
     String n = S.next();
     int sum = 0;

     for (int i = 0; i < n.length(); i++) {
       sum += Integer.parseInt(n.substring(i, i+1));
     }

     System.out.println(sum);
   }

Note: Replacing the body of the for loop with:

int offset = (n.substring(i, i+1).equals("-")) ? 1 : 0;
sum += Integer.parseInt(n.substring(i, i+1+offset));
i+=offset;

Will allow the program to take negative numbers. Ex: Inputting

-24

Would return a positive 2.

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.