1

I want to know how I would be able to get each individual digit from an integer. See I have this program that adds each individual digit from the integer that was input into the program. However I think that there is a simpler way to do this.

import java.util.Scanner;
public class SumOfDigits
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a number greater than 1");
        int n = in.nextInt();
        int divisible = 10;
        int leftovers = 10;
        int sum = 0;
        while(leftovers <= n * 10)
        {
            int digit = 0;   
            if(n % leftovers < 10)
            {
                digit = n % leftovers;
            }
            else
            {
                digit= n % leftovers / divisible;    
            }

            sum = sum + digit;
            System.out.println(sum);
            leftovers *= 10;
            if(leftovers >= 1000)
            {
                divisible *= 10;
            }
        }
        System.out.println("The sum of the digits is " + sum);
    }
}
resueman
  • 10,572
  • 10
  • 31
  • 45
Yogi_CS
  • 29
  • 1
  • 6
  • 1
    If your current code works this might be a better question for our sister site, [Code Review](http://codereview.stackexchange.com/). – gonzo Dec 09 '15 at 19:23
  • Are you wanting to split one integer, or split multiple integers, they should essentially work the same but I don't see what you are doing above. – liquidsystem Dec 09 '15 at 19:26
  • I just saw "How to get the separate digits of an int number?" and it is the same. I'm new to the stack over flow community and I'm barely getting the flow of this site. Sorry it's a duplicate it won't happen again. – Yogi_CS Dec 09 '15 at 19:30
  • @gonzo I'll check out your website. Thanks – Yogi_CS Dec 09 '15 at 19:30

1 Answers1

3

You want to extract digits out of a number? Like 4, 7 and 8 out of 478?

int value = 478, digit;
while (value != 0) {
    digit = value % 10;
    System.out.println(digit);
    value = value / 10;
}
CVaida
  • 53
  • 4