如果带有字符串比较的语句永远不会运行?
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!");
}
}
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!");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
使用
"yes".equalsIgnoreCase(answer)
。Use
"yes".equalsIgnoreCase(answer)
.使用 <代码>String#equals(),而不是
==
。已经有很多关于此的问题了。在您的情况下,
String#equalsIgnoreCase()
可能更合适:旁注:您将
z
用作布尔标志。不使用int
,而是使用boolean
。Use
String#equals()
, not==
. There are many questions on SO about this already.In your case,
String#equalsIgnoreCase()
might more suitable:Side note: you're using
z
like a boolean flag. Instead of using anint
, use aboolean
.使用 equals 或在您的情况下可能是 equalsIgnoreCase
Use equals or in your case may be equalsIgnoreCase
您想查看
String.equals()
或String.equalsIgnoreCase()
,例如answer.equalsIgnoreCase("yes")
或甚至“yes”.equalsIgnoreCase(answer)
。You want to have a look at
String.equals()
orString.equalsIgnoreCase()
, e.g.answer.equalsIgnoreCase("yes")
or even"yes".equalsIgnoreCase(answer)
.在 String 对象上调用 equals("str") 将会起作用。
==
将引用与字符串进行比较,因为 Java 中的String
是一个对象。Calling
equals("str")
on the String object will work.==
compares references with strings, asString
in Java is an object.您混淆了对象标识和对象相等的概念。
在 Java 编程语言中,等于运算符 (
==
) 测试左侧和右侧操作数是否引用同一个确切对象(也称为引用相等或对象标识);但是,Object#equals(o)
方法(由 String 类重写)测试调用对象是否与其参数“等效”。考虑这些例子:
另一方面:
You are confusing the concepts of object identity and object equality.
In the Java programming language, the equals operator (
==
) tests if the left-hand and right-hand operands refer to the same exact object (aka referential equality, or object identity); however, theObject#equals(o)
method (which is overridden by the String class) tests if the calling object is "equivalent" to its argument.Consider these examples:
On the other hand: