0

I'm trying to write a simple hangman game in java for my college class. For some reason the if statement never returns seems to think that the two substrings being compared are equal. The two print statements show that by all rights the two should equate.

public String guessLetter(String letter)
{
    String blanks = "";
            String theWord="FOO";
    for(int i=0; i<=theWord.length()-1; i++)
    {
        System.out.print(letter.substring(0,1).toUpperCase());
        System.out.print(theWord.substring(i,i+1)+ "\n");

        if((letter.substring(0,1).toUpperCase())==(theWord.substring(i,i+1)))
        {
            blanks = blanks + theWord.substring(i,i+1);
        }
        else
        {
            blanks = blanks + "___  ";
        }           
    }
    return blanks;
}

EDIT - As a great many people have pointed out, when comparing Strings, one must use the equals method instead of ==. I was unaware.

tjtoml
  • 331
  • 2
  • 5
  • 13

3 Answers3

2

You are comparing a String so use "String".equals() dont use ==

use like this:

if((letter.substring(0,1).toUpperCase()).equals(theWord.substring(i,i+1)))
ashokramcse
  • 2,841
  • 2
  • 19
  • 41
  • 1
    Why `==` doesn't work? What is it comparing? I think explanation will be very helpful to OP. – Maroun Feb 21 '14 at 10:27
  • == checks for identity. That is whether the two objects are the same object and point to the same address in memory. .equals() by default does the same thing, but can be overridden to perform different equality comparisons. (i.e. strings are considered equal if they have the same characters in the same order) – ashokramcse Feb 21 '14 at 10:30
1

if((letter.substring(0,1).toUpperCase())==(theWord.substring(i,i+1))) \ this is wrong for strings

When you compare strings you should use .equals or .equalsIgnorecase

if((letter.substring(0,1).toUpperCase()).equals(theWord.substring(i,i+1)))

ans also checkout the difference between == and .equals in java good explanation is given there.

Ashish
  • 1,943
  • 2
  • 14
  • 17
1

Java dont have == for string
you must use string1.equals(string2) function

Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
Mahdi-bagvand
  • 1,396
  • 19
  • 40