Jump to content
  • Advertisement
Sign in to follow this  
Nanook

Help with a method [java]

This topic is 3871 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I've been trying to write a method that takes the string word (one singel word ) and the string input(a string with a longer text). The method is going to search for the word in the string.. I know there is some built in methods in the String type I can use for this, but I want to make my own just to learn.. Heres the source code. I cant seem to find out where its going wrong.
	public static int searchWord(String word, String input)
	{
		int count = 0;
		for(int i = 0; i < input.length(); i++)
		{
			int charN = (int)input.charAt(i);
			if (charN > 96 && charN < 123)
			{	
				StringBuffer sWord = new StringBuffer();				
				sWord.append(input.charAt(i));
				for(int j = (i + 1);j < input.length(); j++)
				{
					charN = (int)input.charAt(j);
					if (charN > 96 && charN < 123)
						sWord.append(input.charAt(i));
					else
					{
						if (sWord.toString() == word)
							count++;
						i = j + 1;
						break;
					}
				}	
			}	
		}
		return count;
	}

Share this post


Link to post
Share on other sites
Advertisement
Without testing your code, what I can see is that you are using the equals-operator for comparing the strings. As you may know, in Java, when comparing reference type objects (objects not of a primitive type), == compares the addresses of the objects. What you want, though, is to compare the actual string content. This you do using the equals method.

Another thing. When you assign the return value from the charAt method, you are using an int type variable, to later compare it to the ASCII codes of specific characters. You do not have to use the ASCII codes for this, but can instead compare it to the actual characters. Neither do you need an int for this; you could use a char directly. The code below is not tested.

char c = input.charAt(i);
if (c >= 'a' && c <= 'z')
{
//Do stuff
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!