-1

我正在尝试制作一个基本的“20 个问题”类型的东西来学习如何使用带有布尔比较器(如 &&)的 if 语句。然而,我的“如果”陈述不是,呃,“做”(对不起),即使他们的标准得到满足(据我所知)。

当我编译时,无论我输入什么“答案”,我得到的唯一输出是“我会问你是否正确......” ALA:

Think of an object, and I'll try to  guess it!
1. Is it an animal, vegetable, or mineral?vegetable
Is it bigger than a breadbox?yes
I'd ask you if I'm right, but I don't really care

我尝试了谷歌搜索,但我觉得我错过了一些如此基本的东西,以至于我没有看到它。这是代码:

Scanner keyboard = new Scanner(System.in);
    String response1, response2;

    System.out.println("Think of an object, and I'll try to "
            + " guess it!");
    System.out.print("1. Is it an animal, vegetable, or mineral?");
    response1 = keyboard.next();

    System.out.print("Is it bigger than a breadbox?");
    response2 = keyboard.next();

    if(response1 == "animal" && response2 == "yes")
    {
        System.out.println("You're thinking of a moose");
    }
    if(response1 == "animal" && response2 == "no")
    {
        System.out.println("You're thinking of a squirrel");
    }
    if(response1 == "vegetable" && response2 == "yes")
    {
        System.out.println("You're thinking of a watermelon");
    }
    if(response1 == "vegetable" && response2 == "no")
    {
        System.out.println("You're thinking of a carrot");
    }
    if(response1 == "mineral" && response2 == "yes")
    {
        System.out.println("You're thinking of a Camaro");
    }
    if(response1 == "mineral" && response2 == "no")
    {
        System.out.println("You're thinking of a paper clip");
    }

    System.out.println("I'd ask you if I'm right, but I don't really care");

在此先感谢任何回复者!

4

4 回答 4

1

你必须比较像这样的字符串

if(response1.equals("animal")){

// do something 
}

==比较确切的值。所以它比较原始值是否相同,

String#.equals()调用对象的比较方法,该方法将比较references. 在 的情况下Strings,它会比较每个字符以查看它们是否为equal

于 2013-07-22T09:10:54.243 回答
0

您应该使用equals()不比较字符串==

使用您的示例:

if(response1.equals("animal") && response2.equals("yes"))
{
    System.out.println("You're thinking of a moose");
}...
于 2013-07-22T09:11:15.460 回答
0

您的代码问题与字符串比较有关,与“&&”运算符无关。使用equals方法进行字符串比较。'==' 检查两个引用是否指向同一个内存对象。

替换您的 if 检查以进行字符串比较

if(response1 == "animal" && response2 == "yes")

if("animal".equals(response1) && "yes".equals(response2))

这是一个相关的帖子,可以更多地了解java中的字符串比较

Java String.equals 与 ==

于 2013-07-22T09:13:47.250 回答
0

比较字符串值使用equalsIgnoreCase

if(response1.equalsIgnoreCase("animal")){

 //process
}

这里有条件检查布尔值

于 2013-07-22T09:15:01.260 回答