Using the getSize method

Write a method calledgetSize( int num ) that takes an integer number as input argument and returns the number of digits in that number.
If have already ask the user to enter a number.  Which he can enter something like 34566.
I then want to use the getSize method to find out the number of digits in that number.
I tried it first by converting my interger to astring to count the amouth of characters used but it didn't work.

staticint getSize (int num) //taking the # that they have already inputed.
{
     int count = 0;

     return count =(String.valueof(num)).length();
}

Can someone pleasehelp

Ashia

Your code is working fine....just try to use String.valueOf(num) once again.

Hirpara

Its verysimple, you don't need to convert the number into String.

staticint getSize (int num)
{
     int count = 0;
     while (num!=0)
    {
        num = num / 10;
// above line truncates last digit forevery
// iteration and when num becomes zero, count
// will haveno.of digits.
        count++;
     }
     return count;
}

I think this will solve your problem,

Nagesh

What Nagesh told works fine, however, if you want to do it by converting the 'int' to a 'string'..here is a way to do it...

void getSize(int num){
  String s;
  s = Integer.toString(num);
  System.out.println(s.length());
 }

Vinay

Do you have a Java Problem?
Ask It in The Java Forum

Java Books
Java Certification, Programming, JavaBean and Object Oriented Reference Books

Return to : Java Programming Hints and Tips

All the site contents are Copyright © www.erpgreat.com and the content authors. All rights reserved.
All product names are trademarks of their respective companies.
The site www.erpgreat.com is not affiliated with or endorsed by any company listed at this site.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
 The content on this site may not be reproduced or redistributed without the express written permission of
www.erpgreat.com or the content authors.