This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Sum the digits of an integer. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Sum the digits of an integer." Watch "Sum the digits of an integer." New topic

Sum the digits of an integer.

MaryEllen Volb
Ranch Hand

Joined: Jan 31, 2001
Posts: 35
I have already gotten one good response to this one, but now I can't understand how to extract the digits so I can sum them together (2 + 3 + 4 =9). Anyone got any great idea?
Here's the code I already got:
public class Test{
public static void main(String[] args){
int i = 234;
private static void sumDigits(int digits){System.out.println("digits before calculation: " + digits);int sum = 0;
sum += digits % 10;
digits /= 10;
System.out.println("sum: " + sum);System.out.println("digits after calculation: " + digits);
}} Thanks!!!Mary Ellen
huiying li
Ranch Hand

Joined: Feb 12, 2001
Posts: 68

MaryEllen Volb
Ranch Hand

Joined: Jan 31, 2001
Posts: 35
Thanks....I'll try it!!! Mary Ellen
Pat Barrett
Ranch Hand

Joined: Jan 03, 2001
Posts: 63
The first thing is to separate the digits. If you take a 3 digit number and divide by 100, your answer will be a single digit representing the hundreds place. Now, if you take that same 3 digit number and get the modulus of a division by 100, you will be left with the tens and units places, represented as a 2 digit number. Take that 2 digit number, divide by ten and you'll have the 10's place, the modulus of the 2 digit number divided by 10 will be the units place.
Let's try 123..
123 / 100 = 1 ( the hundreds place )
123 % 100 = 23 ( the remainder )
23 / 10 = 2 ( the tens place )
23 % 10 = 3 ( the units place )
Sum up the hundreds, tens & units and you'll have your answer.

Pat B.
MaryEllen Volb
Ranch Hand

Joined: Jan 31, 2001
Posts: 35
Yes, it did help so much.....thanks....I wouldn't be getting thru my class if not for all the help I find here!!!

Mary Ellen
Vnese Programmer

Joined: Jul 14, 2013
Posts: 1
Thank you Mr/Ms Pat Barrett for the beneficial answer. I resolved the problem. Cheers!
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: Sum the digits of an integer.
It's not a secret anymore!