go to previous page   go to home page   go to next page

Answer:

1 + number of X in the tail = 11


X counter

The number of Xs in the string is easily calculated if you know how many there are in the tail:

  1. If a string has no characters, then the number of Xs is 0.
  2. Otherwise,
    • if the first character is X, then the number of Xs is
      1 + Xs in the tail
    • if the first character is not X, then the number of Xs is
      0 + Xs in the tail

Recall that str.substring(1) evaluates to the tail of the string, and that str.charAt(0) evaluates to the first character of the string.

Also recall that str.substring(1) evaluates to the empty string when the string has only one character.


public class XTester
{
  public static int xLength( String str )
  {
    if ( str.isEmpty() ) 
      return ;
      
    else if ( str.charAt(0) == 'X' )
      return  + xLength( str.substring(1) );
      
    else
      return  + xLength( str.substring(1) );
  }
   
  public static void main (String[] args)
  {
    String str = "XabcaXvw, tuwXcbXXXw, qityrsmnX; XXX123eryiop[X]";
    
    System.out.println( "Number of Xs in " + str + " is: " + xLength( str ) );
  }
}

QUESTION 10:

Fill in the blanks.


go to previous page   go to home page   go to next page