1. Member
Join Date
Aug 2008
Posts
31
Rep Power
0

## String Exercise

Given a string, count the number of words ending in 'y' or 'z' -- so the 'y' in "heavy" and the 'z' in "fez" count, but not the 'y' in "yellow" (not case sensitive). We'll say that a y or z is at the end of a word if there is not an alphabetic letter immediately following it. (Note: Character.isLetter(char) tests if a char is an alphabetic letter.)

countYZ("fez day") → 2
countYZ("day fez") → 2
countYZ("day fyyyz") → 2

The problem says two loops. Here's my algorithm but I dont know how to implement it (im not so good with the character/string class):

Look for a space using indexOf(' '). Once you find the space, go back one index and see if it is a y or z... if it is.. raise the globalCount once.

Look at the end of the string using the .length() method. If the end of the string is y or z... add the global count.

Can anyone show me the light?

2. your best bet is to give it a try first and try to implement the code yourself, then come back with this code if it doesn't work. Just throwing in the towel without first putting in some effort will guarantee that you'll never learn Java.

3. Member
Join Date
Aug 2008
Posts
31
Rep Power
0
Hi. I wanted to know if my logic is correct first before I coded. Is there a better algorithm than the one that I said?

4. seriously man, the best test of your logic is to code it and run test sentences through it.

5. Member
Join Date
Jun 2008
Posts
39
Rep Power
0
class CountChars
{
public static void main(String arg[])
{
String str = "day fyyyz";
String sp[] = str.split(" ");
int count = 0;
for(int i=0;i<sp.length;i++)
{
if(sp[i].endsWith("z") || sp[i].endsWith("y"))
count++;
}
System.out.println(" Count chars ========= " + count);
}
}

6. jithan... a couple of things... it's not a good idea to post complete code to OPs... too much temptation to cut & paste & forget. There's no learning process.
Another thing is that the code that you posted doesn't use the assignment specifications. You can get the OP in trouble ...

Luck,
CJSL

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•