jeudi 23 novembre 2017

Trouble with Loop to Count Number of Given Characters in a String

I have to use a provided loop to count the number of times the character 'b' appears in a String fourthString and for some reason it's returning an incorrect number. I believe it has to do with the if condition but I could be mistaken.

Any help would be HUGELY appreciated.

The string:

String fourthString = "a bat for baseball";

It should return 3.

The format for the code:

char target        ='b';                               
int  length        = fourthString.length( );               
int  count         = 0;                                
int  startNxtSrch  = 0;                                
int  foundAt       = 0;                               

while( ....... )
{
  foundAt = .......;
  if ( ....... )
  {
    startNxtSrch = foundAt +1;
    count += 1;
  }  
  else
    startNxtSrch = length;
}  
System.out.printf( "%nThere are %d occurrences of '%c' in fourthStr.%n", 
                   count,
                   target );

What I tried that is returning an incorrect number:

int i = 0;

while( i < length )
{
  foundAt = startNxtSrch;
  if ( fourthString.indexOf('b', startNxtSrch) != -1 )
  {
    startNxtSrch = foundAt +1;
    count += 1;
    i++;
  }  
  else
    startNxtSrch = length;
  i ++;
}  
System.out.printf( "%nThere are %d occurrences of '%c' in fourthStr.%n", 
                   count,
                   target );

Aucun commentaire:

Enregistrer un commentaire