Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

length of integers

 
Thomas Whalen
Ranch Hand
Posts: 123
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
is it possible to get the length of an integer? i have tried converting an integer to a string, then getting the length of that variable. but, it seems to be returning only the literal value of the variable.
here is my code:
// create months variable
int months = 3456;
// make String copy of months variable
String cp_months = Integer.toString(months);
// print length of cp_months
System.out.print("\nLength is " + cp_months.length);
this is boggling me. i looked at the String and Integer classes in the API, don't see anything that deals with getting the length of anything but an array.
 
Marilyn de Queiroz
Sheriff
Posts: 9059
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Thomas Whalen:
is it possible to get the length of an integer? i have tried converting an integer to a string, then getting the length of that variable. but, it seems to be returning only the literal value of the variable.
here is my code:
// create months variable
int months = 3456;
// make String copy of months variable
String cp_months = Integer.toString(months);
// print length of cp_months
System.out.print("\nLength is " + cp_months.length());

So you're getting a result of 4 for this, right (after you put the parens on length()). What length are you looking for?
 
Thomas Whalen
Ranch Hand
Posts: 123
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i was only using VariableName.length ...is that why i am getting the literal value of VariableName ? as i was reading my Thinking in Java book last night i saw where Bruce was using the VariableName.length() method to get the number of integers in the variable.
 
Marilyn de Queiroz
Sheriff
Posts: 9059
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can't get it to compile using cp_months.length.

cannot resolve symbol
symbol : variable length
location: class java.lang.String
System.out.print("\nLength is " + cp_months.length );

length is a property of an array. length() is a method of the String class.

If I use
System.out.print("\nLength is " + cp_months );
I get the literal String referenced by cp_months.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic