我只是想用HashSet测试随机数的分布密度,请各位看看下面这个程序有什么问题??

robotcrawl 2003-03-14 09:10:13
//:用HashSet测试随机数的分布密度
import java.util.*;

class count implements Comparable { //定义Set对象 
public static int cnt;
private int i = 1;
public count(int num) {
i = num;
}
public boolean equals(Object a) {
return (a instanceof count) && (((count)a).i == i);
}
public int compareTo(Object a) {
int ai = ((count)a).i;
return((ai > i) ? 1 : ((ai == i) ? 0 : -1));
}
public int hashCode() {
return i;
}

public String toString() {
return "count" + i +" cnt:" + cnt + "\n";
}
}


public class Randtestset { //主函数main
public static void main(String[] args) {
HashSet hs = new HashSet();
Iterator it = hs.iterator();
boolean added = false;
int Randint;
count cn;
count currElem;
for(int i = 0; i < 10; i++) {
Randint = (int)(Math.random() * 20);
System.out.println(Randint);
cn = new count(Randint);
it = hs.iterator();
while(it.hasNext()) {
System.out.println("one");
currElem = (count)it.next();
if(cn.equals(currElem)) {
currElem.cnt++;
added = true;
}
}
if(!added) {
hs.add(cn);
added = false;
}
}
}
}
...全文
17 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
takecare 2003-03-14
  • 打赏
  • 举报
回复
呵呵,cnt应该是static,因为他要计数出现重复的值的次数。
不过楼上的说的也有道理,这样就不能体现分布。
robotcrawl 2003-03-14
  • 打赏
  • 举报
回复
结帖,给分!!
rexwang 2003-03-14
  • 打赏
  • 举报
回复
cnt怎么能是static的呢!你应该需要多个拷贝呀,否则大家多用一个变量,何来分布呢
takecare 2003-03-14
  • 打赏
  • 举报
回复
很好,但有一点小修改。
“boolean added = false;”放到for循环里去,要不然一旦出现added=true以后,即便是新的数据也不能添加进去了。

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧