看起来编译器无法将 nextLine() 值识别为字符串

It looks like compiler doesn't recognize nextLine() value as string

        Scanner scan = new Scanner(System.in);
        AccountList accounts = new AccountList();
        
        accounts.addAccount(new BankAccount(100000, "Mark", "BA0021"));
        accounts.addAccount(new BankAccount(367000, "John", "BA0022"));
        accounts.addAccount(new BankAccount(94500, "Michael", "BA0023"));
        
        accounts.accessAccount("BA0021").checkBalance();
        String temp = "BA0022";
        accounts.accessAccount(temp).checkBalance();
        **temp = scan.nextLine();
        accounts.accessAccount(temp).checkBalance()**;

如你所见,我试过了:

        **temp = scan.nextLine();
        accounts.accessAccount(temp).checkBalance();**

像我尝试并成功的其他两种方法一样:

        accounts.accessAccount("BA0021").checkBalance();
        String temp = "BA0022";
        accounts.accessAccount(temp).checkBalance();

并且控制台显示:

Mark's  balance is 0000
John's  balance is 7000
**BA0023
Cannot Find an Account That Matches the ID**
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "ainsof26.project.banking.BankAccount.checkBalance()" because the return value of "ainsof26.project.banking.AccountList.accessAccount(String)" is null
    at BankingApplication/ainsof26.project.banking.BankingApplication.main(BankingApplication.java:22)

你能认出这里的问题是什么吗?

这是 accessAccount 方法:

BankAccount accessAccount(String id) {
        for(BankAccount account: accountList) {
            if(account.clientId == id) {
                return account;
            }
        }
        System.out.println("Cannot Find an Account That Matches the ID");
        return null; 
    }

正如 Slaw 所指出的,错误来自 checkBalance() 方法。我相信作为参数传递给此方法的帐号未关联到任何帐户,因此 checkBalance() returns null (因为没有 Account 对象与该帐户关联).

这可能是由于 scan.nextLine() 读取了整行。你可以通过

来测试
String s = scan.nextLine();
System.out.println(s.length());

对于"8102 "的输入,长度将为8(4个数字和4个空格)。你最好使用 scanner.next();因为它一次读取一个单词,并且通过使用空格作为终止符来实现。

String s = scan.next();
System.out.println(s.length());

对于"8102 "scan.next()读取的字符串长度为4。

此外,checkBalance()方法中的字符串比较应替换为.equals()方法。