[英]Java unreachable code error to do with object initialisation
因此,我在Eclipse(無法訪問的代碼)中遇到錯誤。 我認為這可能是因為我正在while循環內調用對象方法。 但是我需要在while循環中聲明它,因為用戶輸入必須滿足某些要求。
這是main方法中的代碼段:
double startMoney = 0;
AccountBasic PrimaryAccount = new AccountBasic(startMoney);
System.out.println("How much £ would you like to begin with in the format of £0000.00?");
startMoney = input.nextDouble();
while (true) {
PrimaryAccount.deposit(startMoney);
}
System.out.println("Your available balance is £" + PrimaryAccount.getBalance()); //unreachable code
這是來自對象類的代碼:
public class AccountBasic extends StockAccount
{
public AccountBasic(double initialBalance)
{
super(initialBalance);
}
public void withdraw(double amount)
{
balance -= amount;
}
public void deposit(double amount)
{
while (true)
{
if (amount > 500)
{
System.out.println("Please deposit an amount between £1 - £500");
continue;
}
else if (amount <= 500)
{
balance += amount;
break;
}
}
}
public double getBalance()
{
return balance;
}
}
該代碼無法訪問,因為您有一個while循環,它將無限期地運行到時間的盡頭。 當true等於true時運行的while循環。 嘗試更改while循環,使其結束或完全擺脫它。
由於此代碼塊,您遇到了無法到達的代碼錯誤:
while (true) {
PrimaryAccount.deposit(startMoney);
}
由於您沒有提供退出循環的方法,因此該循環將始終評估為true(顯然),因此將永遠運行。
while循環永遠不會停止。[無限循環]
while (true) {
PrimaryAccount.deposit(startMoney);
}
通過更新條件或使用break語句使其停止
你有一個無限循環
while(true)//Condition is always true
因此,無法退出該循環,因此該循環之后的代碼將永遠不會執行。
提供退出循環或break
或更改條件的方法。
我認為您可以返回方法“ deposit”的布爾值,從那里刪除while true,如果存款正確則返回。 像那樣:
public boolean deposit(double amount)
{
if (amount > 500) {
System.out.println("Please deposit an amount between £1 - £500");
return false;
}
else if (amount <= 500) {
balance += amount;
return true
}
}
然后,您可以循環詢問這樣的輸入:
while (true) {
startMoney = input.nextDouble();
if (PrimaryAccount.deposit(startMoney)) {
break;
} else {
continue;
}
}
PS:通常我們使用駝峰式命名約定,因此您的變量“ PrimaryAccount”將更好地命名為:
AccountBasic primaryAccount = new AccountBasic(startMoney);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.