The following code is part of a searchengine
the specific piece of code sorts out the different searching options.

While running it i get the catch (Exception e) error

import java.util.*;

public class ObtainKey 
{
	public static void KeyAnalyzer()
	{
		int idx = 0;
		int tokenCount;
		String input;
		String inputArr[] = new String [10];
		System.out.println("Enter Search Key :");
		Scanner getKey = new Scanner(System.in);
		input = getKey.nextLine();
		StringTokenizer st = new StringTokenizer(input);
		tokenCount = st.countTokens();
		while (st.hasMoreTokens())
		{
			inputArr[idx]=st.nextToken(); idx++;
		}
		int position = 0;
		if (tokenCount == 1)
		{
			System.out.println("Looking for : " + inputArr[0]);
		}
		if (tokenCount == 2)
		{
			System.out.println("Looking for : " + inputArr[0] + " , " + inputArr[1] + "words");
		}
		try
		{
			for (position=0; position<inputArr.length; position++)
			{
				if (inputArr[position].contains("and"))
				{
				System.out.println("Looking for " + inputArr[position-1] + " and " + inputArr[position+1]);
				}
				else if (inputArr[position].contains("AND"))
				{
				System.out.println("Looking for " + inputArr[position-1] + " AND " + inputArr[position+1]);
				}
				else if (inputArr[position].contains("or"))
				{
				System.out.println("Looking for " + inputArr[position-1] + " or " + inputArr[position+1]);
				}
				else if (inputArr[position].contains("OR"))
				{
					System.out.println("Looking for " + inputArr[position-1] + " OR " + inputArr[position+1]);
				}
				else if (inputArr[position].contains("\""))
				{
					System.out.println("Looking for " + inputArr[1] + " And " + inputArr[2] + " words with proximity.");
				}
			}
						
		}
		catch (Exception e)
		{
		System.err.println("Error: " + e.getMessage());
		}
	}	
}

Any ideas ?

Recommended Answers

All 4 Replies

Change your println statement to e.printStackTrace(); and it will tell you which line the error is occurring on.

Most likely it is an ArrayIndexOutOfBoundsException which is going to be thrown. You initialize the array to be of size 10, then in your later else if statements add one (1) onto it. This would be fine in the first few loops but when you get to loop 9 and try and add one to it, your program will throw the exception noted above.

You are probably right, but if he posted the exception and stack trace, people wouldn't have to guess nor trace his code and he may have gotten it sorted out much quicker.

Well
cale.macdonald was right.
Managed to do this with proper if statements.

Firstly thanks for the comments and suggestions.
And secondly about saving lots of time, going back to the books and searching for possible errors takes so much time.

Ezzaral next time i will do.
Didn't think of it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.