当前位置: 代码迷 >> J2SE >> 如何是个死循环
  详细解决方案

如何是个死循环

热度:282   发布时间:2016-04-24 17:55:22.0
怎么是个死循环?
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]);
}
}
编译没有错误!但是个死循环!请高手帮忙搞定一下!(我要的是一百个不重复的随机数)

------解决方案--------------------
你有一个小错误
s.add(new Integer((int)Math.random()*100)); 改成
s.add(new Integer((int)(Math.random()*100))); 就可以了
不然的话你的随机数永远是0(因为Math.random得到的是大于0小于1的数,再转换成int还是0),当然死循环了.
  相关解决方案