我在使用nextLine()获取字符串时遇到了困难,然后将其用作测试条件(在if语句或while循环中)。看看println(),似乎String被正确地分配给变量'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");
}
}
答案 0 :(得分:2)
你应该使用equals。 ==
为您提供引用相等性,equals
为您提供价值相等。
if("yes".equals(repeat)){
而不是
if(repeat == "yes"){
我会建议您获取eclipse / net beans并开始调试,否则简单的搜索会产生答案
答案 1 :(得分:1)
if(repeat == "yes"){
应该是
if(repeat.equals("yes"){
(或)
if("yes".equals(repeat){
我们每天都会看到这个问题很多次,简单的搜索可以为您提供足够的信息。
==
等于原始比较(引用相等)。 equals()
用于String(或)Object比较(对象内容相等)。
答案 2 :(得分:1)
有时候==应该用于对象,但实际比较的是a和b是否真的是同一个对象(在内存中具有相同的地址)。正如其他人所说,你在这种情况下比较内容,所以你使用.equals()