这是代码:
导入java.util.Scanner;
哈罗公共课{
public static void main(String[] args) {
System.out.println("What is your name?");
Scanner firstScanner = new Scanner(System.in);
String imput = firstScanner.nextLine();
if (imput.length() > 6 ) {
System.out.println("That's quite a long name!");
}
else {
System.out.println("A nice and consise name you have.");
}
imput = firstScanner.nextLine();
if (imput == "Thank you") {
System.out.println("Yes, so how many siblings do you have?");
}
else {
System.out.print("Aren't you suppose to say 'Thank you' when someone complements you?");
}
}
}
当我在控制台中键入“谢谢”时,它仍然显示“有人补充您时,您不应该说'谢谢'吗?” 即使我输入的内容与我声明的完全相同。为什么不问我有多少个兄弟姐妹?
抱歉,这很难理解。
这是因为==
Java中的运算符比较两个值是否相同。对于这样的基元,int
它可以正常工作。但是object和String
s是对象,它比较两个对象是否相同,而不是它们的内容是否相等。
可能存在两个不同的String对象,它们表示完全相同的文本,但是是两个不同的对象。
因此,请务必使用
string1.equals(string2)
或者
string1.equalsIgnoreCase(string2)
用于字符串比较。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句