-1
注意:累積直方圖是一個直方圖,其中每個值都添加到之前值的總和中,例如,如果有3個蘋果,2個香蕉和6個桔子,則正常直方圖中的數字將[3,2,6],但在累積直方圖中,它們將是[3,5,11]。覆蓋創建子類的方法
問題:創建一個名爲CumulativeHistogram的直方圖的子類。我只需要重寫toString()方法來解決問題。
class Histogram
{
public char symbol = '*';
protected String[] categories;
protected int[] frequencies;
public Histogram(int numCategories)
{
categories = new String [ numCategories ];
frequencies = new int [ numCategories ];
for (int index = 0; index < numCategories; index++) {
categories[index] = "unlabeled";
frequencies[index] = 0;
}
}
public void setCategory(int index, String name, int frequency)
{
categories[ index ] = name;
frequencies[ index ] = frequency;
}
public String toString()
{
String result = "";
for (int index = 0; index<categories.length; index++){
result+=categories[index] +": ";
result+=repeatSymbol(frequencies[index]);
result+="\n";
}
return result;
}
protected String repeatSymbol(int numTimes)
{
String result = "";
for (int index = 0; index <numTimes; index++)
result += symbol;
return result;
}
}
這裏是類模板:
class CumulativeHistogram extends Histogram {
public CumulativeHistogram(int numCategories) {
super(numCategories);
}
public String toString() {
//*****fill in this method
}
}
一些測試代碼
Histogram hist = new Histogram(3);
hist.setCategory(0, " Apples", 4);
hist.setCategory(1, "Bananas", 2);
hist.setCategory(2, "Oranges", 5);
println(hist);
CumulativeHistogram hist2 = new CumulativeHistogram(3);
hist2.setCategory(0, " Apples", 4);
hist2.setCategory(1, "Bananas", 2);
hist2.setCategory(2, "Oranges", 5);
println(hist2);
,其輸出
Apples: ****
Bananas: **
Oranges: *****
Apples: ****
Bananas: ******
Oranges: ***********
有超過一個隱含的,毫無疑問這裏,其他。答案是,不。 –
問題是如何重寫一個方法?這不是功課,不要太傲慢。 – chv
答案在文中。它說「填寫此方法」的位。這是行動中的優先。編寫代碼來執行你需要的任何功能。 –