2017-02-15 48 views
-8

我是java的新手,我必須編寫withdraw方法來檢查帳戶是否有足夠的數據。
如果帳戶餘額低於0,它只會打印出一條消息Insufficient funds如何在java中返回雙重方法的字符串

我已經試過如下:

public double withdraw(double accountbalance) { 
    if(accountbalance <= 0) { 
     return "Insufficient funds"; 
    } 
} 
+4

不應該這種方法**減去**的東西?另外,'print'!='return'。 –

+4

我個人會拋出異常'InsufficientFundsException ** **但是**我們真的需要知道這個方法應該做什麼的邏輯,以及**如何叫做 –

+1

'要去零以下,但零是不要低於零,你應該使用'<而不是'<='。 –

回答

0

基於方法名withdraw(...),我相信它應該是在這裏有減,應該有accountbalancewithdrawAmount不足值應該accountbalance<withdrawAmount

您需要修改返回類型從doubleString

public String withdraw(double accountbalance) 
{ 
    if(accountbalance <=0){ 
     return "Insufficient funds"; 
    } 
    return "Suffcient"; 
} 

另外,我建議恢復double,如果沒有足夠的價值,只是返回0,否則返回您請求

+0

這給了我以下錯誤:返回類型與Account.withdraw不兼容(雙) – jack

+3

@Michael你的問題也不會自行編譯。你想'返回'一個'字符串'或'返回'一個'雙'? –

+0

@ cricket_007我需要它返回一個字符串 – jack

0

更改您的返回類型爲字符串,而不是雙

public String withDraw(double accountbalance) { 
    if(accountbalance<=0) { 
     return "Insfufficient funds"; 
    } 
    return "Money is there"; 
} 
+0

爲什麼-1給出答案這是每個問題的正確答案 – user2844511

+0

我不知道誰下調這些答案。他們都是有效的。我給他們所有的投票 – Ryan

+0

如果你從字面上理解這些問題,那麼這些答案是正確的,但是他們並沒有解決問題背後的問題,用戶是Java的新手,可能是一般的編程。背後的問題是如何根據特定條件切換返回類型。如果沒有足夠的資金,該字符串只能返回__。否則,需要另一種返回類型。 –

0

你需要回報的金額一個String沒有雙重 並且必須在if之外。例如:

public String withdraw(double accountbalance) 
    String str=""; 

    if (accountbalance <= 0) 
    { 
    str="Insufficient funds"; 
    } 
    return str; 
} 
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 documentationone of the many tutorials關於該主題。