Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Beginning Java and the fly likes Problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Problem" Watch "Problem" New topic


Ali Khan

Joined: Sep 27, 2005
Posts: 18
I am trying to learn Java thru studying a booklet. I came across this problem from the book that has really confused me.

Write an application that inputs one number consisting of five digits from the user, separates the number its individual digits and prints the digits separated from one another by three spaces each. For example, if the user types in the number 42339, the program should print

4 2 3 3 9

[Hint: You will need to use both division and modulus operations to pick off each digit]

Assume that the user enters the correct number of digits. What happens when you execute a program and type the number with more than five digits? What happens when you execute the program and type a number with fewer than five digits?

I do not understand how the division and modulus operators can make this problem have 3 spaces between the 5 numbers input. I know how to use inputs but this problem has me confused. Can someone please help me in the right direction?
Joel McNary

Joined: Aug 20, 2001
Posts: 1824

The division and modulus are not there to get the three spaces, but rather to obtain the individual digits from the number. If you had the integer 42339, how do you get the number in the hundred's position? You could convert it to a string, get the third-from-last character, and convert that back to a number. But what if your number was 43? You'd have to write in the logic to check for out-of-bounds exceptions.

With division and modulus, you can get the number without any extra checking. Exactly how to use division and modulus is left as an exercise to the reader, as I suspect that that is the point of the exercise.

As an aside, if I were doing this problem, I'd convert the number to a string and then print out each character spaced with three spaces. Since the solution is non-mathematical, that would suffice. However, I suspect that the goal is see how division and modulus work, so follow that approach.

Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
To get started print 42339 % 10 and see if the result looks useful in your problem.

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
I agree. Here's the link:
subject: Problem
It's not a secret anymore!