幾個更亂評:
import java.lang.String;
是多餘的,因爲在包裝java.lang
所有類都在每一個Java源文件自動導入。
- 投票不能小數。人們不能投票0.75候選人A和0.25候選人B.如果您使用整數數據類型(
int
或long
),您將更好地反映這一事實。此外,當你開始獲得像379857.999999
這樣的結果時,你將會節省很多頭痛。這是因爲浮點類型有更好的範圍,但精度更差(使用純整數時尤其明顯)。
- 根據Java通常的命名約定,變量名應該以小寫字母開頭。
- 函數
getTallies
的一個更好的名稱是printTallies
。
- 出於輸出目的,使用字符串格式比連接更好。一些優勢是:支持多種格式,易用性和國際化。
把所有一起:
private int democratVotes;
private int republicanVotes;
public void printTallies() {
System.out.format("Democrats: %,d%n",democratVotes);
System.out.format("Republicans: %,d%n",republicanVotes);
}
在此特定情況下,票將印有千個分離(例如:的3,345,623
代替3345623
)。檢查Java的Formatting Numeric Print Output教程。
思考它更好的,也有一些替代方案,其中getTallies
將有效地返回某種形式的價值:
1)使其既吻合返回String
。但是,以後分離計數器會很困難且效率低下。
public String getTallies() {
return "Democrats: %,d votes. Republicans: %,d votes.%n".format(democratVotes,republicanVotes);
}
2)讓它返回一個數組。
public int[] getTallies() {
return new int[2]{ democratVotes, republicanVotes };
}
public int[] getTallies1() { // Same as getTallies, but written step by step.
int[] result= new int[2] ;
result[0]= democratVotes ;
result[1]= republicanVotes ;
return result ;
}
3)讓它返回一個類。
public VotingMachineResults getTallies() {
return VotingMachineResults(democratVotes,republicanVotes) ;
}
public static class VotingMachineResults {
private int democratVotes;
private int republicanVotes;
public VotingMachineResults(democratVotes,republicanVotes) {
this.democratVotes= democratVotes ; // `this` required to disambiguate field democratVotes from parameter democratVotes.
this.republicanVotes= republicanVotes ;
}
public int getDemocratVotes() {
return democratVotes ;
}
public int getRepublicanVotes() {
return republicanVotes ;
}
}
正如你所看到的,這個類非常相似VotingMachine1
,但它不接受內部狀態的變化。這是一個「價值」班。
不要擔心關於downvotes。一些用戶認爲該網站應該只接受「專家」問題。這可能是,但這不是我的意見。也許我們應該排列/標記問題,以便每個人只看到他/她喜歡的問題。 +1 –