gpt4 book ai didi

java - 无法使 if 语句起作用

转载 作者:太空宇宙 更新时间:2023-11-04 07:59:16 26 4
gpt4 key购买 nike

Possible Duplicate:
How do I compare strings in Java?

import java.util.Scanner;

public class stringComparer {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.println ("Enter 1 word here - ");
String word1 = scan.next();

System.out.println ("Enter another word here - ");
String word2 = scan.next();

if (word1 == word2) {
System.out.println("They are the same");
}
}
}

我大约 10 分钟前让它工作,改变了一些东西,现在由于某种原因它不显示“它们是相同的”?它真的很简单,但我看不出我哪里出了问题。

谢谢!

最佳答案

== 运算符通过引用来比较对象

要查明两个不同的 String 实例是否具有相同的值,请调用 .equals()

因此,替换

if (word1 == word2)

if (word1.equals(word2))

关于java - 无法使 if 语句起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13105820/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com