简体   繁体   中英

If statement oddly not working properly…can't figure it out

So this is a silly question but for some reason this isn't working for me. This is a small part of a little program I am trying to do and I am debugging but a simple if statement isn't working for some reason. Here is the following code:

System.out.println("Enter a command (Enqueue, Dequeue, or Quit): ");
String expr = input.next();
System.out.println(expr);
if (expr=="Enqueue") {
   System.out.println("Enqueue");}

So it should simply grab the input, and if I type Enqueue into the prompt it should print it out. The problem is that it isn't doing it. When I check the value of the variable expr it does show up as the string Enqueue but it doesn't go in and print it.....odd. Is there something dumb I am missing?

You want

if (expr.equals("Enqueue")) {

== is not safe to use with Strings. That operator compares the two references for equality, which will only be true when the two references point to the same instance . In this case, you have two different instances that have the same value . To do value comparisons, we use .equals() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM