gpt4 book ai didi

java - 设置数组值 = 0 且缺少 return 语句

转载 作者:行者123 更新时间:2023-12-01 07:22:22 25 4
gpt4 key购买 nike

我有一个 BankAccount 类

public class BankAccount {
private double balance;

public BankAccount() {
balance = 0;
}

public BankAccount(double initialBalance) {
balance = initialBalance;
}

public void deposit(double amount) {
balance = balance + amount;
}

public void withdraw(double amount) {
balance = balance - amount;
}

public double getBalance() {
return balance;
}
}

我在 BankAccountGroup 类中还有一个包含这些类的数组

public class BankAccountGroup {
private BankAccount[] bankAccounts;

public BankAccountGroup(BankAccount[] bankAccounts) {
this.bankAccounts = bankAccounts;
}

public double getBalance(int i) throws NullPointerException {
return bankAccounts[i].getBalance();
}

public double removeAccount(int i) throws NullPointerException {
if(bankAccounts[i] != null) {
return bankAccounts[i].getBalance();
bankAccounts[i] = null;
}

else {
return 0;
}
}
}

在方法 public double removeAccount(int i) 中,如果第 i 个帐户不为空,我想返回该帐户的余额,然后在索引处的数组元素中将该索引设置为 null我为空。如果该元素已经为 null,则返回 0。

然后我收到错误

D:\CS 140>javac assignment03\BankAccountGroup.java
assignment03\BankAccountGroup.java:17: error: unreachable statement
bankAccounts[i] = null;
^
assignment03\BankAccountGroup.java:23: error: missing return statement
}
^

我知道无法访问的语句错误对于编译器来说基本上是毫无意义的代码,但我不明白为什么。至于 no return 语句,该方法可以采用的两个路径中显然都有 return 语句。我唯一的想法是removeAccount中的if中的两行应该交换,但是我不能将第i个元素设置为null。

最佳答案

您不能将业务代码放在“return”语句之后,因为它将永远无法到达...当您“返回”时,您就从该方法中“退出”。

试试这个:

 public double removeAccount(int i) throws NullPointerException {
if(bankAccounts[i] != null) {
double result = bankAccounts[i].getBalance();
bankAccounts[i] = null;
return result;
}

else {
return 0;
}
}

关于java - 设置数组值 = 0 且缺少 return 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32741099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com