Java 我的登录系统没有';不能正确比较

Java 我的登录系统没有';不能正确比较,java,Java,可能重复: 我试图用Java制作一个简单的用户/密码系统。我的代码是: Scanner sc = new Scanner (System.in); System.out.println("Enter Username :"); String username = sc.nextLine(); System.out.println("Enter Password :"); String password = sc.nextLine(); if (username == "a" &

可能重复:

我试图用Java制作一个简单的用户/密码系统。我的代码是:

Scanner sc  =  new Scanner (System.in); 
System.out.println("Enter Username :");
String username = sc.nextLine(); 
System.out.println("Enter Password :");
String password = sc.nextLine(); 
if (username == "a" && password == "b"){
System.out.print("ok");
}


我想使用用户a进行简单登录并通过b,但这不起作用。

始终使用equals()方法检查字符串是否相等

  if (username == "a" && password == "b"){
应该是

if (username.equals("a") && password.equals("b")){
使用
=
运算符检查两个基本体是否具有相同的值,以及两个对象引用是否指向相同的引用


使用.equals()方法检查两个对象是否有意义地相等

要屏蔽密码,请选择类而不是扫描仪:

String username = null;
String password = null;
Console console = System.console();

System.out.print( "Username: " );
username = console.readLine();

System.out.print( "Password: " );
password = new String( console.readPassword());

System.out.println( "Username = " + username );
System.out.println( "Password = " + password );
if (username.equals( "a" ) && password.equals( "b" )) {
   System.out.print( "ok" );
}
另一个加强安全性的建议是:password变量应该是locale,以防被破坏


console.readPassword()返回一个字符数组,您可以在不分配字符串的情况下逐个字符进行比较,即使要编写的代码更多,也更安全(因为我提供的示例代码使用了字符串).

您是否真的如此贪婪,以至于经常提交不完整和低于标准的答案,然后慢慢尝试通过编辑向其添加内容?恭喜你,你已经回答了他的问题,但他不明白为什么必须使用.equals()而不是==。@AlexLynch贪心1000亿美元的东西。。LOL为什么这个问题被关闭为过于本地化而不是完全重复?@Rohit Jain:问题不在于平等,而在于密码管理。
String username = null;
String password = null;
Console console = System.console();

System.out.print( "Username: " );
username = console.readLine();

System.out.print( "Password: " );
password = new String( console.readPassword());

System.out.println( "Username = " + username );
System.out.println( "Password = " + password );
if (username.equals( "a" ) && password.equals( "b" )) {
   System.out.print( "ok" );
}