我是java的新手,我必须编写withdraw
方法来检查帐户是否有足够的数据。
如果帐户余额低于0
,它只会打印出一条消息Insufficient funds
。如何在java中返回双重方法的字符串
我已经试过如下:
public double withdraw(double accountbalance) {
if(accountbalance <= 0) {
return "Insufficient funds";
}
}
我是java的新手,我必须编写withdraw
方法来检查帐户是否有足够的数据。
如果帐户余额低于0
,它只会打印出一条消息Insufficient funds
。如何在java中返回双重方法的字符串
我已经试过如下:
public double withdraw(double accountbalance) {
if(accountbalance <= 0) {
return "Insufficient funds";
}
}
基于方法名withdraw(...)
,我相信它应该是在这里有减,应该有accountbalance
和withdrawAmount
,不足值应该accountbalance<withdrawAmount
您需要修改返回类型从double
到String
public String withdraw(double accountbalance)
{
if(accountbalance <=0){
return "Insufficient funds";
}
return "Suffcient";
}
另外,我建议恢复double
,如果没有足够的价值,只是返回0,否则返回您请求
更改您的返回类型为字符串,而不是双
public String withDraw(double accountbalance) {
if(accountbalance<=0) {
return "Insfufficient funds";
}
return "Money is there";
}
为什么-1给出答案这是每个问题的正确答案 – user2844511
我不知道谁下调这些答案。他们都是有效的。我给他们所有的投票 – Ryan
如果你从字面上理解这些问题,那么这些答案是正确的,但是他们并没有解决问题背后的问题,用户是Java的新手,可能是一般的编程。背后的问题是如何根据特定条件切换返回类型。如果没有足够的资金,该字符串只能返回__。否则,需要另一种返回类型。 –
你需要回报的金额一个String没有双重 并且必须在if之外。例如:
public String withdraw(double accountbalance)
String str="";
if (accountbalance <= 0)
{
str="Insufficient funds";
}
return str;
}
我认为,负面账户余额是一个例外,因此应该这样实施。
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关于该主题。
不应该这种方法**减去**的东西?另外,'print'!='return'。 –
我个人会抛出异常'InsufficientFundsException ** **但是**我们真的需要知道这个方法应该做什么的逻辑,以及**如何叫做 –
'要去零以下,但零是不要低于零,你应该使用'<而不是'<='。 –