简体   繁体   English

如果声明奇怪地不能正常工作......无法弄明白

[英]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. 这是我正在尝试做的一个小程序的一小部分,我正在调试但是一个简单的if语句由于某种原因不起作用。 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. 所以它应该只是抓取输入,如果我在提示符中键入Enqueue,它应该打印出来。 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. 当我检查变量expr的值时,它确实显示为字符串Enqueue但它不会进入并打印它.....奇数。 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 . 该运算符比较两个引用的相等性,只有当两个引用指向同一个实例时才会为true。 In this case, you have two different instances that have the same value . 在这种情况下,您有两个具有相同值的不同实例。 To do value comparisons, we use .equals() . 要进行值比较,我们使用.equals()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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