Have people really understood the problem? The problem is not how you find out whether a number divides by 3 (as Rusty Shackleford correctly says "if(n % 3 == 0)" is a lot easier).
The problem is how to add up the transverse sum (
ts) of
n = a number's digits in decimal. You see,
n - ts always divides exactly by 3, so if
ts divides exactly by 3, then
n divides exactly by 3. [It also works for dividing by 9.]
What happens when you write "myScanner.nextInt()" is that the program reads the next
int, which is a 32-bit two's complement signed integer. What you hoped you would read from the keyboard is the next digit, which forms part of that
int number when it is written out in decimal (=denary) numerals. You can't do that with nextInt(). There are ways to read a single character from the keyboard, but they are hard to work with.
What you need to do is to find out how to get a number like 59973 (which does, by the way, divide exactly by 3), and type it from the keyboard.
Your Scanner object
(kbi) will give you an input of, would you believe, 59973.
So far, so good. You
don't need 5 tries with the scanner to read a 5-digit number. You need one. One kbi.nextInt(); statement will read a 1-digit number or an 8-digit number just as easily.
Now you need to divide up your number 59973 into 5 9 9 7 and 3.
Do you know anything about iteration (repetition or loops) yet? It ought to be very easy to set up a loop which takes off successive digits (3 then 7 then 9 then 9 then 5 is much easier than 5 then 9 then 9 then 7 then 3).
If you don't know about iteration, you will have to make sure to stick to 5-digit numbers, and take each digit off in a line all of its own.
Then add them all together. Then see whether what you have divides exactly by 3.
By the way, Rusty, your second suggestion
if(g != 0)
is not only easier than
if(0 < g && g > 0)
; it will actually work. You didn't notice that
if (0 < g && g > 0) always returns
false.
I hope that lot makes things clearer rather than obscuring things.
CR
By the way: If rather than verifying that a number whose transverse sum adds up to an exact multiple of 3 divides by 3, you would prefer to
prove it, I know how to do that too.
[ June 04, 2006: Message edited by: Campbell Ritchie ]