-1

I am using Netbeans 7.1.2 IDE. My code is here:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)         {                                         
    // TODO add your handling code here:
    String search1;
    search1 = jTextField1.getText();
    search1.toLowerCase();
    jTextField2.setText("tes1");
    // stone
    if (search1=="stone" || search1=="rock" || search1=="1")
    {
        jTextField2.setText("Stone: 1");
    }

    // grass
    else if (search1=="Grass" || search1=="grass")
    {
        jTextField2.setText("Grass: 2");
    }

    // dirt
    else if (search1=="Dirt" || search1=="dirt" || search1=="Soil" || search1=="soil")
    {
        jTextField2.setText("Dirt: 3");
    }

    // cobblestone
    else if (search1=="cobblestone" || search1=="cobble")
    {
        jTextField2.setText("Cobblestone: 4");
    }

    else;
    {   
        jTextField2.setText("Unknown Block");
    }
}     

When I run the build, and I input 'stone' into jTextField1, and hit jButton1, it just gives me "Unknown Block", when an If statement specifies that it should set jTextField to "Stone: 1". Am I doing something wrong? Sorry if this ends up being a completely obvious error.

Rocmalone
  • 35
  • 1
  • 1
  • 3

5 Answers5

5

Compare String using equals()

if (search1.equals("stone") || search1.equals("rock") || search1.equals("1"))

Read this for more information.

== compares references,not the values. In your case, you want to check for the value equality, not the reference equality.


EDIT:

Remember, you need to do all your String comparisons that way.

Besides,

you have an unwanted ; here:

  else;
    {   
        jTextField2.setText("Unknown Block");
    }

remove that ; after else.

Community
  • 1
  • 1
Kazekage Gaara
  • 14,972
  • 14
  • 61
  • 108
1

You need to use the .equals to check strings, like so:

if (search1.equals("stone") || search1.equals("rock") || search1.equals("1"))

npinti
  • 51,780
  • 5
  • 72
  • 96
1

So first don't compare String using == but use equals() instead then in the last else statement you have add a ; that means the end of the else (so jTextField2.setText("Unknown Block") is always executed). You should drop it.

else; //<==Remove the ;
{   
    jTextField2.setText("Unknown Block");
}
alain.janinm
  • 19,951
  • 10
  • 65
  • 112
0

You should do what Kazekage Gaara is telling. But in this instance the problem is not that. in the following statement remove the ; after else.

else;
{   
    jTextField2.setText("Unknown Block");
}

What happens here is

{   
    jTextField2.setText("Unknown Block");
}

gets executed anyway because it's after the if else blocks. Semicolon effectively terminates the else statement.

Thihara
  • 7,031
  • 2
  • 29
  • 56
0

Use .equals instead of == to comapre strings. See: http://blog.enrii.com/2006/03/15/java-string-equality-common-mistake/

VanessaBR
  • 128
  • 1
  • 1
  • 7