帮助。我是Java编程的新手,所以我会尽力使用你的术语。 我想知道如何让这个程序注册为真。当我输入“password”作为输入时,它不会执行“if”正文中的任何代码。我还将此代码粘贴到另一个类中,无论如何它仍然无效。
我已经为这个程序工作了大约半个小时,并且调试了两倍的时间。请仔细查看编码。
import java.util.Scanner;
public class whileloop {
public void whileloop1() {
//DEBUG THIS PROGRAM! "password" does not work for input
System.out.println("Please enter the password to continue: ");
Scanner password = new Scanner(System.in);
String passwordinput = password.nextLine();
System.out.println("This is your entered password: " + passwordinput);
if (passwordinput == "password") {
System.out.println("Startup sequence has been iniciated.");
System.out.println("System is working correctly.");
//Terminate all here ---
} else {
System.out.println("Wrong password! Terminating program. /END");
}
System.out.println("Supressing the program's scanner!");
password.close();
}
}
答案 0 :(得分:1)
在比较Java中的字符串内容时,使用 .equals()方法。 ==运算符检查引用相等性,这意味着,测试它们是否是同一对象的引用。
所以,在你的情况下:
if(passwordinput.equals("password"))
答案 1 :(得分:1)
这已经多次说了,但是当我比较java中的字符串时,如果你想知道它们是否指向相同的引用使用==
运算符,我会再说一遍。如果您想检查它们是否相等,请使用.equals("somestringhere")
在您的情况下使用passwordinput.equals("password")
答案 2 :(得分:0)
因为,Java
行:
String s;
声明对String
对象的引用,与C++
不同,后者可声明String
的对象。
因此,如果(passwordinput == "password")
比较"password"
的引用和passwordinput
的引用,则结果将为false。
因此,请使用if(passwordinput.equals("password")
,将referenced
与passwordinput
的对象"password"
与{{1}}进行比较