我不知道怎么问这个问题,所以我在下面添加了示例代码(我也试着在谷歌上搜索,但我读到的东西让我比以前更迷茫)
假设有一个名为account的类具有arg构造函数、default构造函数、getter和setter。
public class Account{
private String name;
private String password;
}
public Account(String name, String password){ //default constructor
this.name = name;
this.password = password;
}
public void setName(String name){
this.name = name;
}
public void setPassword(String password){
this.password = password;
}
public String getName(){
return name;
}
public String getPassword(){
return password;
}
然后我使用main中的用户输入创建了2个account对象:
ArrayList<Account> accounts = new ArrayList<Account>();
for(int i=0; i < 2; i++){
System.out.print("What is acc name: ");
String name = input.nextLine();
System.out.print("What is acc password?: ");
String password = input.nextLine();
Account acc = new Account (name, password);
accounts.add(acc);
}
现在arraylist帐户有2个acc对象。
如果我想创建一个“login”选项,用户在其中输入他们的名字,我必须在arraylists对象中找到字符串名称。
这是我目前掌握的代码:
System.out.print("Enter your name: ");
String namecheck = input.nextLine();
System.out.print("Enter your password: ");
String passwordcheck = input.nextLine();
if(accounts.contains(namecheck)){
int index = accounts.indexOf(namecheck);
accounts.get(index).getPassword();
if (passwordcheck.equals(accounts.get(index).getPassword()){
System.out.println("Name and Password matched! You are now logged in. ");
accounts.get(index).setloggedIn(true);//included in original code, for do while loop purposes.
}
else{
System.out.println("No match found");
accounts.get(index).setloggedIn(false); //included in original code, for do while loop purposes.
}
}
它确实不起作用,我想这是因为我使用 accounts.contains()
以及 accounts.indexOf()
.
我试图在arraylists对象中定位一个特定的名称字符串的原因是,这样我就可以得到它的索引,然后将对象中的密码与用户输入的密码进行比较。
如果有帐户对象,名称为peter,密码为:d123。我希望能够定位哪个/或者一个对象是否包含名称peter。
有人知道该怎么做吗?有更聪明的方法吗?先谢谢你。
暂无答案!
目前还没有任何答案,快来回答吧!