简单登录Java程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20034260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple login Java program
提问by Jesper Bruun Hansen
I'm very new to Java, and I want to make a very simple login Java-program. Don't think about security issues and such in this example, I just need help to get it right. My "Account informations" has to be stored in an Array.
我对 Java 很陌生,我想制作一个非常简单的登录 Java 程序。在这个例子中不要考虑安全问题等,我只需要帮助来解决它。我的“帐户信息”必须存储在一个数组中。
This is my code: -- MAIN --
这是我的代码:--主要--
import java.util.Scanner;
public class BATM {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String username;
String password;
System.out.println("Log in:");
System.out.println("Indtast username: ");
username = input.nextLine();
System.out.println("Indtast password: ");
password = input.nextLine();
users check = new users(username, password);
if(check.auth())
System.out.println("You are logged in");
}
}
-- users ---
-- 用户 ---
public class users {
private String username;
private String password;
private String[][] accounts = {{"jesper", "abc123"},{"christian", "abc123"}};
public users(String user, String pass){
username = user;
password = pass;
}
public boolean auth(){
if((username == accounts[0][0]) && (password == accounts[0][1]))
return true;
else
return false;
}
}
I guess this should be a quite simple function, but for some reason the if-statment will never return "true".
我想这应该是一个非常简单的函数,但由于某种原因,if 语句永远不会返回“true”。
What am I doing wrong?
我究竟做错了什么?
Jesper.
杰斯珀。
采纳答案by subash
try this..
尝试这个..
if((username.equals(accounts[0][0])) && (password.equals(accounts[0][1])))
回答by Uku Loskit
you are doing the string comparison wrong, in java you need to use .equals()
isntead of ==
the latter compares two object references, this is not what you want.
你做的字符串比较错误,在java中你需要使用
后者比较两个对象引用的.equals()
isntead ==
,这不是你想要的。