如何解决为什么比较这些字符串不起作用? JAVA初学者
我正在尝试读取正在运行的控制台输入。但是,我的if语句(检查我的输入和期望的输入是否相同)不起作用。我在底部添加了所有代码,如果您发现我做错了,请告诉我。我是Java的新手,所以也给我一些有关代码其他部分的提示。谢谢,马克斯。
package Issue;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class Issue {
public static int loop;
public static String input,desiredInput;
public static void main(String args []) throws InterruptedException {
Scanner in = new Scanner(System.in);
loop = 1;
while(loop == 1) {
input = in.nextLine();
desiredInput = "help";
// uncomment to see if what input and desired input are equal to :)
//System.out.println(input + " " + desiredInput);
if(input == desiredInput) {
System.out.println("911 what's the emergency.");
}
}
}
}
解决方法
您要学会避免使用Java的一些优势。 double equals'=='不应用于对String对象或与此相关的任何对象进行值比较。对于字符串,请使用
input.equals(desiredInput)
,
==
测试引用是否相等(它们是否是同一对象)。
.equals()
测试值的相等性(在逻辑上是否为“相等”)。
您正在此处比较对象引用。字符串是Java输入中的对象== requiredInput表示您正在检查对象引用而不是内容的相等性。要比较内容,请使用input.equals(desiredInput)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。