2 回答

TA貢獻1801條經驗 獲得超16個贊
編寫一個方法:
public void incrementScore(int amount) {
score += amount;
}
是否允許負增量?如果沒有,請檢查它:
/**
* Increments the score by the given amount.
*
* @param amount the amount to increment the score by; must not be negative
* @throws IllegalArgumentException if the amount is negative
*/
public void incrementScore(int amount) {
if (amount < 0) {
throw new IllegalArgumentException("The increment must not be negative.");
}
score += amount;
}
這種方法比使用 /更優雅,因為:getset
它允許您檢查參數,再考慮業務規則,
它添加了一個業務方法,其名稱可以揭示意圖。
它允許您編寫描述操作確切行為的JavaDoc注釋

TA貢獻1829條經驗 獲得超4個贊
正如評論中所說,您可以在學生班級上創建新方法。
public class Student {
private String name;
private int score;
public void incrementScore(int increment){
this.score = this.score + increment;
}
}
然后在 std 實例上調用它:
std.incrementScore(10)
添加回答
舉報