File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes arrays Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "arrays" Watch "arrays" New topic


Julie Mendez

Joined: Oct 04, 2004
Posts: 7
I'm trying to write a program that takes an integer number as input argument and returns the number of digits in that number. This is what I came up w/ so far. In my main program I ask them to enter some integers. And now i want to get the size of the integers they enter in so i can assign it to an array. (or can this only be used for javascript.

static int getSize(int num)
int count = 0;

return count = num.length;

} //ends getSize
[ October 25, 2004: Message edited by: Julie Mendez ]

<b><i>To err is human but to really mess up the things you need a computer </b></i>
Jeff Bosch
Ranch Hand

Joined: Jul 30, 2003
Posts: 805
Hi, Julie-

num is an int, which is a primitive data type, not an array, so you can't check its length property because primitive data types don't have a length property.

If num were an array, you would only determine how many elements were in the array, not how many characters were in any of the array elements. But, an int doesn't work like a string -- it doesn't have a number of characters. If you have the user enter a number as a String, then you could use the length method of the String class to get the number of characters the user entered, in this case the number of digits in the number.

Give a man a fish, he'll eat for one day. Teach a man to fish, he'll drink all your beer.
Cheers, Jeff (SCJP 1.4, SCJD in progress, if you can call that progress...)
Jimmy Die
Ranch Hand

Joined: Nov 20, 2003
Posts: 97

Like mentioned before if the users entered them as a string then the .length() method works nicely. Or a recursive method can also work like below.

[ removed a recursive solution that used repeated division by ten, until no number greater than 9 was left, counting once for each division, plus once for any remaining digit -ds ]
[ October 26, 2004: Message edited by: Dirk Schreckmann ]

Jimmy Die
Priyaa V Kumar
Ranch Hand

Joined: Aug 12, 2004
Posts: 32
You have to convert the primitive data type, int to a String and then call the length() method...

[ code removed -ds ]

Hope this helps
[ October 26, 2004: Message edited by: Dirk Schreckmann ]
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
When helping folks to learn, let's prefer hints and nudges over coded solutions.

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
I agree. Here's the link:
subject: arrays
It's not a secret anymore!