与对象初始化有关的Java无法访问的代码错误

时间:2018-02-20 17:05:59

标签: java

所以我在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;
}
}

5 个答案:

答案 0 :(得分:1)

代码无法访问,因为你有一个无限期运行的while循环,直到时间结束。在true时运行的while循环等于true。尝试更改while循环,以便它结束或完全摆脱它。

答案 1 :(得分:1)

由于此代码块,您收到了无法访问的代码错误:

while (true) {
    PrimaryAccount.deposit(startMoney);
}

此循环将始终评估为true(显然),因此永远运行,因为您没有提供突破循环的方法。

答案 2 :(得分:1)

while循环永远不会停止。[无限循环]

    while (true) {
          PrimaryAccount.deposit(startMoney);
    }

通过更新条件或使用break语句使其停止

答案 3 :(得分:1)

你有一个无限循环

while(true)//Condition is always true

因此,没有办法退出该循环,因此该循环之后的代码将永远不会执行 提供退出循环的方法break或更改条件。

答案 4 :(得分:0)

我认为您可以返回方法的布尔值&#34;存放&#34;,从那里删除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:通常我们使用驼峰案例命名约定,因此您的变量&#34; PrimaryAccount&#34;会更好地命名:

AccountBasic primaryAccount = new AccountBasic(startMoney);