0

I've written some code which should take in two words from a user and if they match display "You have won" however it just displays "error"(my else statement) every time even if they match. I'm trying to find out why the if statement does not detect if they match.

import java.util.*;
class testing{
  public static void main(String[] args){
  Scanner in = new Scanner(System.in); //start scanner
  System.out.println("Please enter word 1");
  String userWord =in.nextLine();
  System.out.println("Please enter word 2");
  String userGuessInput = in.nextLine();
    if(userWord == userGuessInput){
      System.out.println("You have won!");
    }
    else{
      System.out.println("error");
    }
 }
}
David_Hogan
  • 125
  • 1
  • 3
  • 14

1 Answers1

2

Use equals() to compare Strings

if(userWord.equals(userGuessInput)){
      System.out.println("You have won!");
    }
    else{
      System.out.println("error");
    }

equals() compare the value of variables and

== tests for reference equality

Check

Community
  • 1
  • 1
singhakash
  • 7,891
  • 6
  • 31
  • 65