1

I'm trying to figure out how to create a method to find a string inside an array and print that string out along with its index. I think the method signature is correct but I can't figure out how to return the string value in the method.

String name = search(array,"Dog"); //the method implementation in main
System.out.println(name);

.

public static int search(String[] array, String key)
{
    for (int i= 0; i< array.length; i++)
        {
         if ( array[i] == key ) 
         return i;  
        }
     return ("Name cannot be found in array);
}
hoaz
  • 9,883
  • 4
  • 42
  • 53
user1780311
  • 25
  • 1
  • 3

7 Answers7

5

You can't return a String from a method that is declared to return int. The most common ways to indicate failure are to return an out-of-range value:

return -1;

Or to throw an exception:

throw new NameNotFoundException("Name cannot be found in array");

Also, this line won't work:

if ( array[i] == key ) 

Strings need to be compared with equals(), not ==. The == operator checks that the strings are the same objects, not that their contents are identical.

if (key == null && array[i] == null ||
    key != null && key.equals(array[i]))

And make sure that you don't call .equals() on a null reference. The above code checks for this possibility.

Community
  • 1
  • 1
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Well, I see at least 3 problems in the OP code there. May be you can address all of them. – Rohit Jain Dec 07 '12 at 21:03
  • I fixed the...obviously stupid mistakes..Then I had an epihpany and made it into a loop using a bool value. Works wonderfully now XD Thanks for the help guys – user1780311 Dec 07 '12 at 21:25
4

Why do you want to return the String? Whoever calls this method already knows what the String is, because they had to provide it in the first place. (Otherwise how would know what you were looking for :P)

also you should be doing array[i].equals(key).

== is for object equality. .equals() is for value equality.

thedan
  • 1,230
  • 2
  • 9
  • 13
1

If you want to return a String, then...your return type should be String, not int.

Also, you shouldn't use == with Strings, or with most objects, use array[i].equals(key) instead.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
1

The biggest question is why implement search when java has already implemented it for you?

 String[] array;
 String val = "Dog";

 if( Arrays.asList(array).contains(val) ){
      System.out.println("your string is found");
 } else {
      System.out.println("your string is found");
 }

Or better yet true to you implementation

 String[] array;
 String val = "Dog";
 String name = ( Arrays.asList(array).contains(val) ) ? val : "Name cannot be found in array";

it should be noted that Arrays.asList DOES NOT COPY the array merely wraps it in a List structure so that it can be treated as a enumerable. The performance of this method is roughly the same as the one your provided.

gbtimmon
  • 4,238
  • 1
  • 21
  • 36
  • So you create a *list* out of an array, just to find out if it contains a value? Talk about inefficient code... – thkala Dec 07 '12 at 21:09
  • Actually Arrays.asList is extremly performant, as there is no data copy performed it merely return a list view of the already existing String[]. Both methods operate in O(n) and would scale the same. There is no reason to avoid this method. -- Learn yo java before you be up in here doubtin me son.... – gbtimmon Dec 07 '12 at 21:13
  • For more see here http://stackoverflow.com/questions/1552783/performance-of-arrays-aslist – gbtimmon Dec 07 '12 at 21:14
  • True the complexity remains the same, and the list creation itself is O(1), but I really think that creating an `indexOf()` method is a better solution. It is cleaner, faster and does not leave any trash for the GC - I have seen applications being slowed down to a halt because of needless object creation like this... – thkala Dec 07 '12 at 21:20
  • Its an anonymous object... It is reaped immediately. The fact is that the solutions in reality are pretty much exactly the same. Only one is easier to read and cleaner. – gbtimmon Dec 07 '12 at 21:47
0

First fix your comparison to use the equals method as:

  if (array[i].equals(key)) 

Also change last return statement as:

  return -1; //string not found

Then simply do this (use array[searchIndex] to get the string):

int searchIndex = search(array,"Dog");
if(i >= 0){
  System.out.println("String="+array[searchIndex] + ", Array Index="+searchIndex);
 }else{
   System.out.println("String not found");
 }
Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73
0

You allready have String value that you are searching. Why you need to return that ? Just return index

int index = search(array,"Dog");
Addict
  • 803
  • 2
  • 9
  • 16
0

you can try this one .............

import java.util.*;  
public class xyz {  
 public static void main(String [] args){  
    String [] sa = {"abc","def","ghi"};  
    Arrays.asList(sa);  
    Arrays.sort(sa);  
    for(String s : sa){  
        System.out.println(s);  
    }  
}  

}