-3
import java.util.Scanner;

public class Main
{
    public static void main(String[] args) 
    {
        Scanner scan = new Scanner(System.in);
        String play = "y";
        System.out.print("Enter something: ");
        play = scan.next();
        System.out.println(play);
        if (play == "Y" || play == "y")
        {
            System.out.println("If test works!!");
        }
        System.out.println("Did it work???");
    }
}

I assume this has something to do with when I press enter, it's storing that as well. I tried changing String play to a char, but then I get errors from Scanner saying it can't change a String to a char.

  • you should look at this [question](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – BrokenFrog Oct 04 '18 at 16:06

1 Answers1

1

You should atmost avoid using “==“ when comparing objects especially strings. “==“ checks for object references. Change the comparison to use .equals method and it should work

if(play.equals(“Y”) || play.equals(“y”))

in case if “play” can be null, the below snippet is more safe.

if(“Y”.equals(play) || y.equals(play))
  • Just want to elaborate on why this is the case for @Dave2point(). Using the == operator on objects compares their references. E.g. (new String("a")) == (new String("a")) will always evaluate to false because two different objects have been created in memory and the references are pointing to two different locations in memory. This is why you need to use .equals() and it will compare the contents of the object rather than their location in memory. TBC – Richard Stokes Oct 04 '18 at 16:33
  • For custom objects, you will need to overload this method yourself to compare the contents of each object. Also "a" == "a" always evaluates to true because Java will optimise the code and create one String object for String literals and store them within shared memory, hence their references will be the same as they will point to the same object. – Richard Stokes Oct 04 '18 at 16:33