2016-01-22 59 views
0

在我的toString方法我所有的變量進行了印刷精美,所有的我的代碼沒有問題的工作。十進制格式的原因「void類型此處不允許」錯誤

我需要編輯以更改小數格式,以便代替我的數字打印1E9或其他任何(更長的浮點數),它實際上會打印非科學記數法版本(123,456,789.00)。

所以在我的toString方法我初始化一個DecimalFormat對象,並實現了它進入我的價值觀。

之前,我就越來越沒有這樣的錯誤「‘無效’類型這裏不允許」,然而落實十進制格式後,現在是給我的錯誤我的其他變量我想打印的所有3。

爲什麼我的DecimalFormat影響其他變量?

import java.text.DecimalFormat; 

public class Project { 
    String projName;  //Name of a project 
    int projNumber;  //Number of a project 
    String projLocation; //Location of a project 
    Budget projBudget;  //Budget of a project 

public Project(double amount) { 
    this.projName = "?"; 
    this.projNumber = 0; 
    this.projLocation = "?"; 
    Budget thisBudget = new Budget(amount); 
    this.projBudget = thisBudget; 
} 

public String getName(){ 
    return projName; 
} 

public int getNumber() { 
    return projNumber; 
} 

public String getLocation() { 
    return projLocation; 
} 

public Budget getBudget() { 
    return projBudget; 
} 

public void setName(String aName) { 
    projName = aName; 
} 

public void setNumber(int aNumber) { 
    projNumber = aNumber; 
} 

public void setLocation(String aLocation) { 
    projLocation = aLocation; 
} 

public boolean addExpenditure(double amount) { 
    return projBudget.addSpending(amount); 
} 

public String toString() { 
    String format = "###,###.##"; 
    DecimalFormat decimalFormat = new DecimalFormat(format); 
    return "\nProject Name:\t\t" + getName() + "\nProject Number:\t\t" + getNumber() + "\nProject Location:\t\t" + getLocation() + "\nBudget:\nInitial Funding\t$" + decimalFormat.applyPattern(String.valueOf(projBudget.initialFunding)) + "\nSpending\t\t$" + decimalFormat.applyPattern(String.valueOf(projBudget.spending)) + "\nCurrent Balance\t$" + decimalFormat.applyPattern(String.valueOf(projBudget.currentBalance)) +"\n\n"; 
} 
} 
+0

'預算thisBudget =新預算(量); this.projBudget = thisBudget;'可以重寫爲'this.projBudget = new Budget(amount);'。 –

回答

1

,由於decimalFormat.applyPattern()輸出類型爲void

可以使用decimalFormat.format(value)方法和它`輸出字符串 所以你可以用它在你的toString方法沒有任何麻煩。

+0

謝謝一堆。如何更改格式以顯示2位小數?例如:19000000.00正在顯示19,000,000 – MaydenCompe

+0

您的歡迎,**'#'**的數量** **確定小數位數後,請考慮'format =「###,###。## 「',現在結果有兩位小數,如果你另一個它會改變像'格式=」###,###。###「'結果將有三個等等 –

+0

這就是我認爲,但它贏了打印出「.00」(我需要完成我的任務)。當我把一些不是0的整數像「.21」一樣的時候,它實際上就是打印出來的。有沒有辦法打印.00? – MaydenCompe

相關問題