我是java新手,我必须使用写withdraw
方法检查帐户中是否有足够的内容。
如果帐户余额低于0
,则会打印出一条消息Insufficient funds
。
我尝试了以下内容:
public double withdraw(double accountbalance) {
if(accountbalance <= 0) {
return "Insufficient funds";
}
}
答案 0 :(得分:0)
根据方法名称withdraw(...)
,我认为应该在此处进行减法,应该有accountbalance
和withdrawAmount
,值不足应该是accountbalance<withdrawAmount
您需要修改从double
到String
public String withdraw(double accountbalance)
{
if(accountbalance <=0){
return "Insufficient funds";
}
return "Suffcient";
}
或者,我建议退回double
,如果没有足够的价值,只需返回0.否则返回您要求的金额
答案 1 :(得分:0)
将您的返回类型更改为String而不是Double
public String withDraw(double accountbalance) {
if(accountbalance<=0) {
return "Insfufficient funds";
}
return "Money is there";
}
答案 2 :(得分:0)
你需要返回一个String no double 并且必须在if之外。例如:
public String withdraw(double accountbalance)
String str="";
if (accountbalance <= 0)
{
str="Insufficient funds";
}
return str;
}
答案 3 :(得分:0)
我认为,负帐户余额是一个例外,因此应该如此实施。
public double withdraw(double amount) {
if (accountBalance - amount < 0) {
// throwing an exception ends the method
// similar to a return statement
throw new IllegalStateException("Insufficient funds");
}
// this is only executed,
// if the above exception was not triggered
this.accountBalance -= amount;
}
现在你可以这样称呼:
public String balance(double amount) {
// to handle potentially failing scenarios use try-catch
try {
double newBalance = this.account.withDraw(amount)
// return will only be executed,
// if the above call does not yield an exception
return String.format(
"Successfully withdrawn %.2f, current balance %.2f",
amount,
newBalance
);
// to handle exceptions, you need to catch them
// exceptions, you don't catch will be raised further up
} catch (IllegalStateException e) {
return String.format(
"Cannot withdraw %.2f: %s",
e.getMessage()
);
}
}
String.format
是一个方便的实用程序,用于格式化Strings
而不会混淆它们。它使用占位符,它们在各自的顺序中以格式String
之后的变量替换。
%s
代表String
。
%f
是占位符,用于浮点数。在上面的例子中,我使用%.2f
将浮点数格式化为小数点后的2位数。
有关异常处理的更多信息,请参阅official documentation或one of the many tutorials中有关该主题的内容。