Aditya kumar Aditya kumar - 2 years ago 76
Java Question

Empty String in an array of strings

I want to calculate the no of letters in words from 1 to 100. for example....

If the numbers 1 to 5 are written out in words: one, two, three, four, five,

then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.

for which I have written the following code...

public static int helper(int a){

String ones[]= {"","one","two","three","four","five","six","seven","eight","nine","ten",

String tens[]= {"","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"};

return ones[a].length();
return tens[a/10].length();

public static int countLetters(int a){
return 10;

else if(a<20){

return helper(a);


return helper((a/10)*10)+ helper(a%10);

The main function looks like

public static void main(String[] args) {
// TODO Auto-generated method stub

int result=0;
for(int i=1;i<=100;i++){


The correct answer for this problem is
. In the
String ones[]
array I used punctuation marks
" "
with space between them. The
returned was
which is incorrect but after removing space between them answer returned was
. I used
without space. I wonder why this happened..?

Is there any logical aspect with respect to strings or string arrays for this problem ?

Answer Source

It only happens when you have the " " in the ones array.

If you have 20, you get the length of "twenty" + the length of helper(a%10) which is helper(0), which returns the length of " ". So you get the length of "twenty" + the length of " ".

This happens for 20, 30, 40, 50, 60 ,70 ,80 and 90. 8 times. That's why you see the 872.

The easiest fix is just making the first string "", like you did, but this would work too:

// return helper((a/10)*10)+ helper(a%10);
return helper((a/10)*10) + (a%10 == 0 ? 0 : helper(a%10));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download