Hi everybody. First of all happy new year to all. Secondly, I am 3 months into learning Java and GUI and I am having some trouble with comparing strings. I am doing hangman and I have a text field set up for when the player wants to guess the entire word and I can't seem to figure out how to compare when they write a word in with the correct word. For example, if the word is "hello" and they type in "hi", how do I compare them to see if what they typed in is the same as the correct word?
This is what I have tried so far:

String word="relationship";
char array[]=word.toCharArray();
if (guessI.equals("relationship"))
{
	System.out.println("Yay it works!!");
}

In what I have tried to write guessI is the text field and relationship is the correct word.
If I am completely mistaken or incorrect in an aspect or completely using the wrong method please explain to me which one would work best.
Thanks a lot.

if guessI is a String and word is a String then you can use the equals or equalsIgnoreCase methods to compare them.

if (guessI.equals(word)) {
// true if guessI and word are exactly the same
}
if (guessI.equalsIgnoreCase(word)) {
// true if they are the same regardless of case
}

There is no need to use a char array.

well dont u need to first getText from the guessI textfield and then compare it to the word string...
like

String g=new String("");
g=guessI.getText();
if(g==word)
//worked;
else
//wrong;

i am also new in java...correct me if i am wrong

Is guessI the String or the JTextField in the GUI? If it is the text field then rajatC is correct :$

Careful rajatC, with Strings you must compare them with the equals() method, as == is intended for primitives and String is an object.

JTextField guessI = new JTextField();
String g = new String("");
g = guessI.getText();
if(g.equals(word))
      //worked;
else
      //wrong;

Thanks so much to everybody, I appreciate a lot the time everybody has given to reply to this question, take care and have a good day!!

Careful rajatC, with Strings you must compare them with the equals() method, as == is intended for primitives and String is an object.

thanks for the suggestion..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.