-1

The if statement does not read the string in the array - tokens[i] so the condition after if does not execute. The string "hot" can not be read. Why is that so? Please help! Thanks.

public static void main(String[] args){

    String str = "Wow! It's getting realy hot in here." ;
    String delims = "[ .,?!/><;:'_!`~/$/@/#/%/&/|/[/]/{/}/)/(]+";
    String[] tokens = str.split(delims);

    for (int i = 0; i < tokens.length; i++){
        if (tokens[i] == "hot"){

            System.out.println("Found!");
            break;
        } 
        else {
            System.out.println("Not found!");
        }
   }     

} 
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
lrayzzor
  • 9
  • 1
  • 3

2 Answers2

6

Use the String.equals(String otherString) function to compare strings.

if (tokens[i].equals("hot")){

Not the == operator.

The reason is that == just compares object references/primitives,where as String's .equals() method checks equality.

Maroun
  • 94,125
  • 30
  • 188
  • 241
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • @Suresh ok it worked fine. Now I have to edit my code so that only "Found" is displayed when the string "hot" is discovered in the text. Thanks alot. – lrayzzor Sep 21 '13 at 12:15
1

This doesn't work because you are using the ==-Operator for comparing Strings.

The ==-Operator checks whether the object reference is the same. This is not the case, because "hot" is not the same reference as tokens[i].

Object.equals() compares the values of the object. For a String, it compares if the character combination is the same. Check the API for more information.

So, use tokens[i].equals(String str).

If case sensitivity doesn't matter, use this method: string.eqaulsIgnoreCase(String anotherString).

Frithjof
  • 2,214
  • 1
  • 17
  • 38