Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

1. Digit counter

Hi everyone, this is my very first post here in jpforums .

Sorry if is not an allowed question,but, there is another way to do this more simple??? (I am a begginner) I suspice that my code is too long and useless. I only want to count the digits that a number has.

```]
static int contarCifras(int num){

int cifras = 1;

String[] nums = new String[8];

// I initialize array to 0   to avoid it start on null, when I convert to integer I get exception
for(int i=0;i<nums.length;i++)
nums[i]="9";

// I add the string "9" to every string of the array
for(int i = 0; i <nums.length;i++)
for(int j = 1; j<=i;j++)
nums[i] +="9";

// I compare if a number is higher than 9, if it is higher, it means it has 2 digit, if higher than 99... 3....
for(int i = 0;i <nums.length;i++){
if(num>Integer.parseInt(nums[i]))
cifras++;
else
break;
}
return cifras;
}```
1º question: I don't know another way to "append" 9 to an integer, if i 9+9 = "18" but i want start at number 9 and append 9 many times, then = "99", next "999"

2º question: It is necesary to start array of strings to "9"?? because I see with debugger that it is null as default so when i append 9 , it is "null9"
and when I parse to integer it throw me "numberformatexception"

thank you.

2. Re: Digit counter

r way to "append" 9 to an integer, if i 9+9 = "18"
Strings allow you to append one character to another with the + operator: "9" + "9" = "99"
With numeric values to get 99 you add 90 and 9. 9 + 90 = 99

The initial values of an array of Strings is null. Set the elements to the empty String: "" to replace the null.

3. The Following User Says Thank You to Norm For This Useful Post:

Rexshine (January 16th, 2013)

4. Re: Digit counter

thank you, I'll not forget about to set strings as: "" when needed,