在这一行if(input==code) 上,您忘记添加左括号,所以只需在末尾添加{。
看起来像
if(input==code) {
System.out.println("Password entered!");
} else {
System.out.println("Wrong password!");
}
为 cmets 编辑
System.out.println("Password entered!"); 从不打印的原因是因为您使用的是== 运算符。当== 运算符用于比较对象时,它会检查对象是否引用内存中的同一位置。基本上,它检查对象名称是否引用到相同的内存位置。不应该使用== 的示例如下:
// Create two Strings with the same text "abc"
String obj1 = new String("abc");
String obj2 = new String("abc");
// Compare the two Strings
if (obj1 == obj2) {
// Will never reach here and print TRUE
System.out.println("TRUE");
} else {
// Will always print FALSE
System.out.println("FALSE");
}
上面的代码总是打印FALSE,因为这两个字符串对象不在内存中的同一个地方——我知道这很混乱!要阐明何时使用==,请参阅下面的代码
// Create a new string object
String obj1 = new String("abc");
// Create another new string object but assign obj1 to it.
String obj2 = obj1; // obj1 and obj2 are now located in the same place in memory.
// Compare the two objects
if (obj1 == obj2) {
// Will always print TRUE
System.out.println("TRUE");
} else {
// Will never print FALSE
System.out.println("FALSE");
}
在上面的代码中,我们的两个对象位于内存中的同一位置,因此在比较每个对象的内存引用时,它们在某种意义上是相等的。
但很明显,您不想比较对象的内存引用,而是要比较每个对象包含的字符串值。所以您需要查看的是equals() 方法,我不会对此进行详细介绍,但它主要比较两个对象值而不是内存位置。看看下面的代码
// Create two Strings with the same text "abc"
String obj1 = new String("abc");
String obj2 = new String("abc");
// Compare the two String values using equals()
if (obj1.equals(obj2)) {
// Will always print TRUE because the two string values
// are equal/the same.
System.out.println("TRUE");
} else {
// Will never print FALSE
System.out.println("FALSE");
}
因此,使用我们刚刚了解的 == 运算符和 equals() 方法,我们可以在您的代码中使用它,因此请尝试更改为
// Using equals because you want to compare the String values
// not the reference to memory location for each object
if(input.equals(code)) {
// Should print true if input value is equal to code value.
System.out.println("Password entered!");
} else {
System.out.println("Wrong password!");
}
如果您还有问题,请发表评论,希望对您有所帮助。