2014-04-08 72 views
0

我正在尝试编写一个BankAccount.java类,除了提取方法外我几乎完成了。我留下了解释我对所写代码的理解的评论意见,但我无法找到导致逻辑错误的原因。似乎无法找到正确的if语句或返回

测试程序的帐户1余额= 100和帐户2余额= 200 提款金额是帐户1 = 100和帐户2 = 201所以显然100应该跟随如果返回和帐户2应遵循其他回报但是,这不是案件。

public int withdraw(double amount) { 
    AccountBalance = this.AccountBalance - amount; // Setting AccountBalance to what it would be when the withdraw amount is subtracted 
    if (0 < AccountBalance) // testing if 0 is less than AccountBalance 
     return (int)AccountBalance; // if so then i return the new positive balance 
    else 
     return (int)AccountBalance + (int)amount; //if less then 0 i return to what the balance was before withdraw was subtracted because i can't have a negative balance 

} 

这是以下输出我在CMD接收:

F:\>java BankDemo 
The balance of account1 is: 100.0 
The balance of account2 is: 200.0 
account1 information: John Smith 
AccountNumber: 12345 
Balance: 0.0 

account2 information: John Calipari 
AccountNumber: 54321 
Balance: -1.0 

上述两个帐户是相同?假

最后,虽然我有可能是这个错误是不是在这种方法和在整个班级不同的方法。我不认为这是事实,因为我有三重检查,但如果这似乎是一种可能性反馈会很好,因为我会把焦点从这种方法转到我班的其他人。

+0

你为什么要投射到'int'?我认为我们可能需要查看更多的代码。 – voidHead

+0

您是否将'AccountBalance'设置为您从此方法返回的金额?如果不是,那么你如何使用返回值?在“否定”情况下,这种方法本身会将“AccountBalance”视为负数。 –

回答

1

如果我对代码的其他部分有所了解,那么无论如何你都要做AccountBalance = this.AccountBalance - amount。这总是会改变余额。当您将该值重新添加到您实际上未设置AccountBalance变量的量时。所以在else块你要添加:

AccountBalance = (int)AccountBalance + (int)amount;

确保选择正确的类型AccountBalance,也变量往往按照惯例小写启动,以便accountBalance所以它可能更容易,如果读取其较低,但不会影响实际结果。

+0

我最近刚刚尝试过这一点,但它仍然适用于使account2 200;现在account1返回等于100而不是0. – user3483201

+0

您需要将您的if语句更改为'<=',因为0是一个有效的账户余额 –

+0

感谢您的帮助,非常感谢。现在程序运行尽可能流畅 – user3483201

1

您的问题是if (0 > AccountBalance)如果AccountBalance为负值则为真,如果为正值则为false;而不是相反。

+0

请原谅我在发布的代码中的错字。我确实按照你的建议采用了它。我的错误,我已经做了必要的编辑 – user3483201

0

你的方法是错误的结帐这一个。

public int withdraw(double amount) { 
    AccountBalance = this.AccountBalance - amount; 
    if (0 > AccountBalance) { // testing if 0 is greater than Account balance 
    return (int)AccountBalance + (int)amount; 
    } else{ 
    return (int)AccountBalance; 
    } 
    } 
0

如果负余额是无效状态,则不应修改成员并检查后缀。

if (AccountBalance >= amount) { 
    AccountBalance -= amount; 
} 
return AccountBalance; 

(缺少类型转换,显示清晰的代码)

我觉得你的测试显示了成员国(的toString()?),而不是方法的返回值。