2009-12-13 69 views
0
public class Histogram 
{ 
private int lo_; 
private int hi_; 
private int[] frequency_; 

public Histogram(int lo, int hi) 
{ 
    lo_ = lo; 
    hi_ = hi; 
    int range = hi_-lo_+1; 
    frequency_ = new int[range]; 
    for(int i =0; i <range; range++) 
     frequency_[i] = 0; 
} 

public void ReadValue() 
{ 
    Scanner in = new Scanner(System.in); 
    int value= in.nextInt(); 
    while(value != -1) 
    { 
     if(value >= lo_ && value <= hi_)    
     { 
      frequency_[value - lo_]++; 
      value = in.nextInt(); 
     } 
    } 
} 

private String starPrinter(int value) 
{ 
    String star = "*"; 
    for(int i = 0; i <= value ;i++) 
    { 
     star +="*"; 
    } 
    return star; 
} 

public String Printer() 
{ 
    String print = new String(); 
    int range = hi_-lo_+1; 
    int i = 0; 
    while(i<range) 
    { 
     print += (lo_+i)+" : "+ starPrinter(i)+ "\n"; 
     i++; 
    } 
    return print; 
} 


public int query(int value) 
{ 
    if (value >= lo_ && value <= hi_) 
    { 
     value -= lo_; 
     return starPrinter(value).length(); 
    } 
    else 
     return -1; 
} 

public static void main(String[] args) 
{ 
    Histogram test = new Histogram(3, 9); 
    test.ReadValue(); 
} 

} 

我需要關於此直方圖的幫助。直方圖頻率幫助Java

由低數量和高數(所以如果我把3 〜9:這些都是它預計的數字,任何其他被忽略)產生的構造

readValue方法會不斷循環,直到用戶類型-1。含義 ,如果我輸入3, 4, 6, 4, 6, 9 , 5, 9, 4, 10 -1 ...那麼它將存儲 所有在frequency[]。我如何使它在frequency[]中跟蹤每個值可以是 ?

3發生一次,4發生三次,7永遠不會發生,9發生兩次

Printer()會讓我看起來像這樣 直方圖圖(使用之前輸入的號碼......)

3: * 
4: *** 
5: * 
6: ** 
7: 
8: 
9: ** 

如何使用打印頻率的數字打印 星號碼發生的數量?

查詢方法會問他們想要什麼號碼的用戶和 告訴他們多少次它發生:

類型3「3出現2次」

類型10「10超出範圍「。

我有大部分的代碼,我只需要幫助實現一些部分。

+0

聽起來像是我的作業問題 – jitter 2009-12-13 00:11:18

回答

1

你已經差不多完成了,有一些愚蠢的錯誤。您的starPrinter方法會打印比應該打印的更多的星星。您應該這樣寫:

private String starPrinter(int value) 
{ 
    String star = ""; 
    for(int i = 0; i < value ;i++) 
    { 
     star +="*"; 
    } 
    return star; 
} 

並且您將錯誤的參數傳遞給starPrinter。它應該是這樣的:

print += (lo_+i)+" : "+ starPrinter(frequency_[i])+ "\n"; 

最後,你必須記得調用它。只需在主底添加一行:

public static void main(String[] args) 
{ 
    Histogram test = new Histogram(3, 9); 
    test.ReadValue(); 
    System.out.println(test.Printer()); // Add this line. 
} 

現在它的工作原理! (只要你不輸入超出範圍的號碼。)