Sign in to follow this  
Nanook

Help with a method [java]

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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this