4 Replies - 758 Views - Last Post: 11 January 2011 - 03:07 PM Rate Topic: -----

#1 dominion_vortar  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 52
  • Joined: 07-November 09

Simple linear search result error

Posted 11 January 2011 - 02:50 PM

Evening!

I've just been playing around with a simple linear search algorithm, and for the most part have got the search working ok. I'm searching an array of just 5 strings, and after the search loop ends, it should either display that it's been found, or not found.

On both counts, however, it shows the result as found even if the search comes back negative. Any help on this would be appreciated, cheers.


	public void search()
	{
		
		boolean found = false;
		int foundIndex;
		String searchTarget = "Mark";

		System.out.println("Search started");

		 
		for (int i = 0; i < studentArray.length; i++)

		   if (studentArray[i].equals(searchTarget)) 
		   {
		        foundIndex = i;
		        found = true;
		        break;
		   }
	
		
			if (found = true)
			{
				System.out.println("Found entry");
			}
			else
			{
				System.out.println("Search term not found");
			}			



Is This A Good Question/Topic? 0
  • +

Replies To: Simple linear search result error

#2 n8wxs  Icon User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: Simple linear search result error

Posted 11 January 2011 - 02:55 PM

 if (found = true)


should be

 if (found == true)


or better

 if (found)

This post has been edited by n8wxs: 11 January 2011 - 02:55 PM

Was This Post Helpful? 0
  • +
  • -

#3 japanir  Icon User is offline

  • jaVanir
  • member icon

Reputation: 1010
  • View blog
  • Posts: 3,025
  • Joined: 20-August 09

Re: Simple linear search result error

Posted 11 January 2011 - 02:55 PM

 if (found = true) 

is this a typo?
should be
if (found == true) 

Was This Post Helpful? 0
  • +
  • -

#4 Petsarve  Icon User is offline

  • New D.I.C Head

Reputation: 5
  • View blog
  • Posts: 45
  • Joined: 17-February 10

Re: Simple linear search result error

Posted 11 January 2011 - 02:59 PM

Your for-loop does not have any braces, so that should not even compile, unless you also have an instance variable that is int i. A for loop should be:
for (int i = 0; i < array.length(); i++) {
  //do loop stuff here
}


Was This Post Helpful? 0
  • +
  • -

#5 dominion_vortar  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 52
  • Joined: 07-November 09

Re: Simple linear search result error

Posted 11 January 2011 - 03:07 PM

View Postn8wxs, on 11 January 2011 - 01:55 PM, said:

 if (found = true)


should be

 if (found == true)


or better

 if (found)


Ahh!! Missed out the other = sign, thanks for spotting that guys :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1