I am writing a small Java program and need help using a simple search code. It is not compiling.

public int indexOf(EltType e) {
        int i=0;
        for (i = currsize; i < currsize; i++){
            things[i] = e;
            e.equalts(get(i));
        }
   
        return -1;
    }

Basically I want to get the position number of each item it searches. Here is the method that calls it:

public void searchtester() {
        MyList<String> searchlist = new MyList<String>();
        searchlist.add("tangerine");
        searchlist.add("apple");
        searchlist.add("mango");
        searchlist.add("lime");
        searchlist.add("carrot");
        for (int i = 0; i<searchlist.size(); i++)
        System.out.println("searching for \"" + searchlist.get(i) + "\", result="
            + words.indexOf(searchlist.get(i)));
    }

Please let me know what I am doing wrong.

Well, if it's not compiling, read the error messages. They are there for a reason.

One question on your search loop: How many times do you figure this will execute

for (i = currsize; i < currsize; i++){

sorry it is compiling now, i had a spelling error but basically I want to search the array for e, and return its position, or -1 if e is not found. Right now all that happens when I call the searchingtester method

searching for "tangerine", result=-1
searching for "apple", result=-1
searching for "mango", result=-1
searching for "lime", result=-1
searching for "carrot", result=-1


even though the first 3 results should return the postion number because they are in the list. I know I have to use .equals(i) to compare e and get(i) but unsure where it goes.

check this out

class searche
   {
     public static void main(String args[])
         {
         String s1="tangerine";
         int d=s1.length();
         int result=0;
       for(int i=0;i<d;i++)
          {
            if(s1.charAt(i)=='e')
             {
              result=1;
             System.out.println("position of e is at "+i);
             }		
           else
             result=-1;
          }		
             System.out.println("result= "+result);	

          
      }
}

check this out

class searche
   {
     public static void main(String args[])
         {
         String s1="tangerine";
         int d=s1.length();
         int result=0;
       for(int i=0;i<d;i++)
          {
            if(s1.charAt(i)=='e')
             {
              result=1;
             System.out.println("position of e is at "+i);
             }		
           else
             result=-1;
          }		
             System.out.println("result= "+result);	

          
      }
}

I haven't read the entire thread, but I don't agree with the code.
The message will be printed when the 'e' is found but the result will not always be 1.
If the String was: "tangerin" the last character would be "n", The loop will check the last character and that will changed the value of result from 1 to -1. Better have this:

class searche
   {
     public static void main(String args[])
         {
         String s1="tangerine";
         int d=s1.length();
         int result=0;
       for(int i=0;i<d;i++)
          {
            if(s1.charAt(i)=='e')
             {
              result=1;
             System.out.println("position of e is at "+i);
              break;
             }		
           else
             result=-1;
          }		
             System.out.println("result= "+result);	

          
      }
}

Or you can initialize result to -1 and when it is found give it the index:

if(s1.charAt(i)=='e')
             {
              result=i;
             System.out.println("position of e is at "+i);
              break;
             }

hi akulkarni, thx for replying to my thread, well i do see what your code is doing but I think what it is doing is searching for letter "e" when in fact what I am trying to do is match the words

"tangerine"
"apple"
"mango"
"lime"
"carrot"

the results are suppose to give me the position of that word or a -1.

i am not clear with what u want. You have taken a list of strings ...what do u want to do with them ..please be specific..match the words (with matching position of e?) is that what u want?

or is this what u want

class searche1
{
 public static void main(String args[])
 {
   int result=0;int i,j;
  String [] str={"tangerline","apple","mango","lime","carrot"};
  for(j=0;j<4;j++)
 {
    for( i=0;i<str[j].length();i++)
    {
       if(str[j].charAt(i)=='e')
      {
         System.out.println("position is "+j);
         result=1;
      }
      else
      result=-1;
   }
   System.out.println(result);
   }


 }
}

Sorry for being more specific, what I want to do is look at those strings then compare it to the MyList which already has strings in them. Here is the code that adds my initial words:

public void initWords(){
        words.add("apple");
        words.add("blueberry");
        words.add("cranberry");
        words.add("daikon");
        words.add("eggplant");
        words.add("figs");
        words.add("grapes");
        words.add("hackberry");
        words.add("jicama");
        words.add("kale");
        words.add("lemon");
        words.add("mango");
        words.add("nectarine");
        words.add("onion");
        words.add("persimmon");
        words.add("quince");
        words.add("rutabega");
        words.add("sorrel");
        words.add("tangerine");
    }

So basically i would want to use that "searchtester()" method to compare it against what I have and give me the position that string is in, if it exists. does that make anymore sense?

sorry typed too quickly, meant to saying "Sorry for NOT being more specific..."

I assume that this: words.add("apple"); is some sort of Vector or ArrayList?
If yes, you can loop the list and compare each element with what you are trying to much.
If found return the index. If none of the elements contain that value return -1

is this it?(sorry if not)

class searche2
{
   public static void main(String args[])
   {
     int result=0;
     String []mylist= {"tangerine","apple","blueberry","mango","jicama"};
     String []tosearch={"tangerine","grapes","blueberry"};
     for(int i=0;i<4;i++)
     {
       for(int j=0;j<3;j++)
       {
          if(mylist[i].equals(tosearch[j]))
         {
         System.out.println("position is "+i);
         result=1;
         }
        else
        result=-1;
     } 
  }
 }
}

u can write the method i guess

Here are some refinements:

class searche2
{
   public static void main(String args[])
   {
     int result=0;
     String []mylist= {"tangerine","apple","blueberry","mango","jicama"};
     String []tosearch={"tangerine","grapes","blueberry"};
     for(int i=0;i<[U]mylist.length[/U];i++)
     {
       for(int j=0;j<[U]tosearch.length[/U];j++)
       {
          if(mylist[i].equals(tosearch[j]))
         {
         System.out.println("position is of: " + mylist[i] + " is: " +i);
         result=1;
         }
/* remove this for reasons described in previous post
        else
           result=-1;
*/
     } 
  }
 }
}

asuming that words is an array list or a vector, modify your method as follows

public int indexOf(EltType e) {
        int i=0;
        for (i = 0; i < words.size(); i++){
            if(words.getElementAt(i)==e)
                  return i;
        }
   
        return -1;
    }

asuming that words is an array list or a vector, modify your method as follows

public int indexOf(EltType e) {
        int i=0;
        for (i = 0; i < words.size(); i++){
            if(words.getElementAt(i)==e)
                  return i;
        }
   
        return -1;
    }

Actually it needs to be:

if(words.getElementAt(i).equals(e) )

If you see the method its perameter is of type "EltType" so "==" will compare the objects. "equals()" can only be used on Strings.

If you see the method its perameter is of type "EltType" so "==" will compare the objects. "equals()" can only be used on Strings.

You couldn't be more wrong than that.

"equals()" is not used to compare Strings. It is used to compare Objects and String is an Object. Also EltType is an Object

Check the API. Read a tutorial. If you don't believe me then I won't bother explaining it to you

Actually I had that concept regarding equals(). I am not very much experienced in Java so I was wrong. Thanks for correcting me.

and now that you believe me the explanation:

When you use "==" on objects you don't compare the value of object but the object itsself. Meaning that you compare if they are the same object. Assuming that I have created a custom class: Person

Person p1 = new Person("name");
Person p2 = new Person("name");

They have the same value but they are 2 different objects.

We use "==" to compare primitive types: int, float, ..
We use equals() to compare Objects: Integer, String, Point, Person

Person p1 = new Person("name");
Person p2 = new Person("name");

System.out.println(p1==p2);
System.out.println(p1.equals(p2));

The above will return
> false
> false (why?)

Because I haven't overridden the equals method in my class. So it will call the one from the super class. The super class is the Object class that checks if they are the same object


THIS:

Person p1 = new Person("name");
Person p2 = p1;

System.out.println(p1==p2);
System.out.println(p1.equals(p2));

The above will return
> true
> true

Because I do this: p2=p1 and I set them to be the same object.

If you want this:

Person p1 = new Person("name");
Person p2 = new Person("name");

System.out.println(p1==p2);
System.out.println(p1.equals(p2));

To return
> false
> true

You need to implement/override the equals method in your class:

public boolean equals(Object o) {
        try {
            Person p = (Person)o;
            return name.equals(p.getName());
        } catch (Exception e) {
        }
        return false;
    }

So the bottom line is that you should always override the methods: equals() and hashCode() whenever you want to put the object in a list or a collection.

Your code is not going to work even if you use the equals(), if your object doesn't override the equals() method.
Of course you need to implement the equals method only in classes that you create. Java classes have already implemented their own, which is why the String.equals works the way it is supposed to

This article has been dead for over six months. Start a new discussion instead.