使用带有“&&”的if语句在Java中,尽管标准得到满足,声明仍未打印

时间:2013-07-22 09:09:38

标签: java if-statement boolean

我正在尝试制作一个基本的“20问题”类型的东西来学习如何使用布尔比较器的if语句,如&&在他们中。然而,即使他们的标准得到满足(据我所知),我的“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 个答案:

答案 0 :(得分:1)

你必须比较像

这样的字符串
if(response1.equals("animal")){

// do something 
}

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

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

答案 1 :(得分:0)

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

使用您的示例:

if(response1.equals("animal") && response2.equals("yes"))
{
    System.out.println("You're thinking of a moose");
}...

答案 2 :(得分:0)

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

替换你的if check(s)进行字符串比较

来自

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

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

这是一篇相关文章,了解有关java

中字符串比较的更多信息

Java String.equals versus ==

答案 3 :(得分:0)

使用equalsIgnoreCase

比较字符串值
if(response1.equalsIgnoreCase("animal")){

 //process
}

条件检查布尔值here