Possible Duplicate:
Java String.equals versus ==
我在使用 nextLine() 获取字符串,然后将其用作测试条件(在 if 语句或 while 循环中)时遇到了困难。查看 println(),似乎字符串已正确分配给变量“repeat”,但测试条件由于某种原因失败了。我的头撞在墙上,额头流血。请帮忙。
import java.util.Scanner;
public class potpie {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
String repeat = "yes";
System.out.println("Type in yes");
repeat = input.nextLine();
System.out.println("If repeat is now yes, print yes: " +repeat);
if(repeat == "yes"){
System.out.println("It worked");
} else
System.out.println("it failed");
}
}
最佳答案
您应该使用等于。 ==
为您提供引用相等性,equals
为您提供值相等性。
if("yes".equals(repeat)){
而不是
if(repeat == "yes"){
我建议您获取 eclipse/net beans 并开始调试,否则简单的搜索就会得到答案
关于java - 使用 nextLine() 后无法创建测试条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13167088/