我有一个 acounts 类,它使用用户名创建一个帐户并登录,并将每个用户保存在列表 account_list 中。我在这个类中有一个方法可以登录将logged_in值从false更改为true。目前我无法调用该函数,因为对非静态方法的静态引用或者通常不确定应该如何调用该方法。我必须在这个分支 Account.java 中保存文件:
import java.util.Scanner;
public class Accounts {
private String username;
private String password;
private Boolean logged_in;
private String account_id;
private Accounts(String username, String password, Boolean logged_in, String account_id) {
this.username = username;
this.password = password;
this.logged_in = logged_in;
this.account_id = account_id;
}
static Accounts createAccount(Scanner scanner) {
System.out.println("Username:");
var username = scanner.nextLine();
System.out.println("Password:");
var password = scanner.nextLine();
return new Accounts(username, password, false, "1");
}
public boolean log_in(Scanner scanner) {
System.out.println("Username:");
var username = scanner.nextLine();
System.out.println("Password:");
var password = scanner.nextLine();
if (username == this.username && password == this.password) {
System.out.println("Logged in sucscefully!");
return this.logged_in = true;
} else {
System.out.println("Log in failed!");
return this.logged_in = false;
}
}
public String toString() {
return "Username: %s Password: %s".formatted(username, password);
}
}
和Project.java
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Project {
private String choice;
public static void main(String[] args) {
List<Accounts> account_list = new ArrayList<>();
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("Welcome to my password database program");
boolean done = false;
while (!done) {
System.out.println("1. Create account \n2. Log in \n3. View passwords \n4. Log out \n5. Exit program");
var choice = scanner.nextLine();
if (choice.equals("1")) {
Accounts account = Accounts.createAccount(scanner);
account_list.add(account);
System.out.println(account);
}else if (choice.equals("2")){
account_list.log_in(scanner)
}else if (choice.equals("5")) {
done = true;
}
}
}
}
}
我对 java 还很陌生,我坚持在控制台中做所有事情,因为我也在 python 中做相同的程序,并且为了更容易在两种语言之间保持一致,我留在控制台中
我尝试将函数设为静态,但它在调用函数方法时不起作用,因为它是一个类。我尝试过相当不安全地调用 account_list 列表中的对象,期望它在调用特定对象时能够工作,但在使其工作时遇到问题,因为我希望能够同时保存大量帐户。
我的拼写很可能很糟糕,因为我患有阅读障碍,而且不是以英语为母语的人。预先感谢!
您当前的代码将无法工作,因为您试图在 ArrayList 本身上调用
log_in
,这不起作用并且没有意义。相反,说实话,我认为您可能想要重新思考并重新编写您的代码。
建议包括:
List<Account> accounts = new ArrayList<>();