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();
}
}我需要在这张直方图上得到帮助。
构造函数是由低数和高数字生成的(因此,如果我将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超出范围。
我有大部分代码,我只需要帮助实现一些部分。
发布于 2009-12-13 00:20:49
你差一点就做了,有几个愚蠢的错误。您的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";最后,你得记住叫它。只需在main末尾再添加一行:
public static void main(String[] args)
{
Histogram test = new Histogram(3, 9);
test.ReadValue();
System.out.println(test.Printer()); // Add this line.
}现在起作用了!(只要您不键入超出范围的号码。)
https://stackoverflow.com/questions/1895120
复制相似问题