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分钟前工作,改变了一些东西现在由于某种原因它没有显示“它们是相同的”?它真的很简单,但我看不出哪里出错了。
谢谢!
答案 0 :(得分:1)
==
运算符通过引用比较对象。
要确定两个不同的String
个实例是否保持相同的值,请致电.equals()
。
因此,请替换
if (word1 == word2)
带
if (word1.equals(word2))
答案 1 :(得分:0)
请尝试此操作,String is not primitive
这样当您检查==
时,它会检查参考文献。
import java.util.Scanner;
/**
* This program compares two strings
* @author Andrew Gault
* @version 28.10.2012
*/
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.equals(word2))
{
System.out.println("They are the same");
}
}
}
答案 2 :(得分:0)