# Digit counter

• January 16th, 2013, 05:16 PM
Rexshine
Digit counter
Hi everyone, this is my very first post here in jpforums :o.

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.

Code java:

```] 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"??:confused: 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.
• January 16th, 2013, 05:38 PM
Norm
Re: Digit counter
Quote:

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.
• January 16th, 2013, 05:53 PM
Rexshine
Re: Digit counter
thank you, I'll not forget about to set strings as: "" when needed,