Java 为什么我的程序不能识别if语句中两个字符串之间的比较?
这是我的代码(下面列出的问题): 导入java.util.Scanner 公共类示例代码{Java 为什么我的程序不能识别if语句中两个字符串之间的比较?,java,if-statement,Java,If Statement,这是我的代码(下面列出的问题): 导入java.util.Scanner 公共类示例代码{ /** * B. Stephens */ public static void main(String[] args) { Scanner input = new Scanner (System.in); String secretPhrase = "show me the money"; boolean notDone = true; while (notDon
/**
* B. Stephens
*/
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
String secretPhrase = "show me the money";
boolean notDone = true;
while (notDone = true){
System.out.print("Guess the puzzle: ");
String puzzleGuess = input.nextLine();
if (puzzleGuess == secretPhrase) {
System.out.println("Congratulations! You guessed the puzzle!");
notDone = false;
}
}
} // end main
由于某些原因,程序无法识别我的输入(拼图猜测)何时与secretPhrase相同。似乎没有理由不让正确的输入结束程序。感谢您的帮助!,因为您需要使用
.equals
方法
if (puzzleGuess.equals(secretPhrase)) {
System.out.println("Congratulations! You guessed the puzzle!");
notDone = false;
}
Java字符串被插入,因此=
有时可以工作
public class InternedDemo {
public static void main(String[] args) {
String s1 = "hello world";
String s2 = "hello world";
String s3 = new String("hello world");
System.out.println(s1 == s2); // true
System.out.println(s1 == s3); // false
System.out.println(s2 == s3); // false
System.out.println(s1.equals(s3)); // true
System.out.println(s2.equals(s3)); // true
}
}
不要使用
=
来比较字符串。使用secretPhrase。equals(猜谜游戏)
=
只是检查两个字符串是否是同一个对象。使用.equals()而不是==
因此,您的if语句应该如下所示:
if(拼图猜测等于(秘密短语))
由于字符串被视为对象,因此必须执行任何对象比较
使用.equals(对象o)
希望我的回答能有所帮助:)使用.equals()与字符串进行比较
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
String secretPhrase = "show me the money";
boolean notDone = true;
while (notDone){
System.out.print("Guess the puzzle: ");
String puzzleGuess = input.nextLine();
if (puzzleGuess.equals(secretPhrase)) {
System.out.println("Congratulations! You guessed the puzzle!");
secretPhrase=null;
notDone = false;
}
}
}
==不能用于比较字符串。对于非原语,==确定它们是否为同一对象。若要查看两个字符串是否具有相同的值,请改用.equals()
什么运算符是相等运算符?它是
=
还是=
?不要使用=
来比较字符串的内容。请改用equals()
。字符串文本是内部的。动态创建的字符串只有在显式执行时才会内部化。任何对象比较都必须使用.equals(对象o)执行.
这样说,你说的是假的。嗨,Sotirios Delimanolis:)你能告诉我为什么是假的吗?我总是用.equals()比较对象(字符串或任何其他类的对象)必须
才是问题所在。这始终取决于您试图做什么。好了,我明白了您的观点:)==可以用于比较字符串或任何其他对象。这是引用相等与实际相等。而(notDone=true)
?
String str1 = new String("foo");
String str2 = str1;
String str3 = new String("foo");
String str4 = new String("bar");
System.out.println(str3 == str3); //true
System.out.println(str1 == str2); //true
System.out.println(str1 == str3); //FALSE!
System.out.println(str1.equals(str3)); //true!
System.out.println(str1 == str4); //false
System.out.println(str1.equals(str4)); //false