怎么是个死循环?

gongyali2005 2007-01-11 09:14:42
import java.util.*;
class MySet
{
public static void main(String [] args)
{
Set<Integer> s=new HashSet<Integer>();
while(s.size()<100)
{
s.add(new Integer((int)Math.random()*100));
}
for(int i=0;i<100;i++)
System.out.println(s.toArray()[i]);
}
}
编译没有错误!但是个死循环!请高手帮忙搞定一下!(我要的是一百个不重复的随机数)
...全文
192 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
cqusgx 2007-01-11
  • 打赏
  • 举报
回复
up
vitren 2007-01-11
  • 打赏
  • 举报
回复
Random ran = new Random();
for (int i = 0; i < 100; i++) {
ran.nextInt(100);
......

有API不用,为什么要自己乘来乘去的?
liuguangyi12 2007-01-11
  • 打赏
  • 举报
回复

s.add(new Integer((int)Math.random()*100));
改为
s.add(new Integer((int)(Math.random()*100))); 就好了.
(int)Math.random()*100)的结果永远是0
先执行(int)Math.random()返回0.再乘几都没用
Voxer 2007-01-11
  • 打赏
  • 举报
回复
你有一个小错误
s.add(new Integer((int)Math.random()*100)); 改成
s.add(new Integer((int)(Math.random()*100))); 就可以了
不然的话你的随机数永远是0(因为Math.random得到的是大于0小于1的数,再转换成int还是0),当然死循环了.
混沌骑士 2007-01-11
  • 打赏
  • 举报
回复
new Integer((int)Math.random()*100)//可能出现重复的值

62,614

社区成员

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

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