如果带有String比较的语句永远不运行?

时间:2011-08-20 19:12:00

标签: java if-statement

import java.util.Scanner;

class Test6
{
    public static void main (String[] args)
    {
        int z = 0;
        while (z != 1)
        {
            System.out.print("Please enter your name: ");
            Scanner x = new Scanner (System.in);
            String name = x.nextLine();
            System.out.print("\n"+"So your name is "+name+"?: ");
            Scanner y = new Scanner (System.in);
            String answer = y.nextLine();
            if ((answer == "yes")||(answer == "Yes"));
            {
                z = 1;
            }
        }
        System.out.println("\n"+"Great!");
    }
}

6 个答案:

答案 0 :(得分:2)

使用"yes".equalsIgnoreCase(answer)

答案 1 :(得分:1)

使用String#equals(),而不是==。已经有many questions on SO了。

if ("yes".equals(answer) || "Yes".equals(answer));
{
    z = 1;
}

在您的情况下,String#equalsIgnoreCase()可能更合适:

if ("yes".equalsIgnoreCase(answer));
{
    z = 1;
}

旁注:你使用z就像一个布尔标志。不使用int使用boolean

boolean z = true;
while (z)
{

}

答案 2 :(得分:1)

您想要查看String.equals()String.equalsIgnoreCase(),例如answer.equalsIgnoreCase("yes")甚至"yes".equalsIgnoreCase(answer)

答案 3 :(得分:1)

使用equals或在您的情况下可能是e​​qualsIgnoreCase

if(answer.equalsIgnoreCase("yes"))
 {

 }

答案 4 :(得分:0)

在String对象上调用equals("str")将起作用。

if(answer.equals("yes") || answer.equals("no"))
{
   z = 1;
}

==将引用与字符串进行比较,因为Java中的String是一个对象。

答案 5 :(得分:0)

您对object identity and object equality的概念感到困惑。

在Java编程语言中,equals运算符(==)测试左手操作数和右手操作数是否指向相同的对象(也称为引用相等或对象标识);但是,Object#equals(o) method(由String类覆盖)测试调用对象是否与其参数“等效”。

请考虑以下示例:

String s = "foo";
s == s; // => true, because the variable "s" obviously refers
// to the same object as itself.  They are "identical".

另一方面:

String a = new String("foo");
String b = new String("foo");
a == b; // => false, because there are two separate objects.
// However...
a.equals(b); // => true, because the strings have the same
// character sequences.  They are "equal".