如何得到4位的随机整数?谢谢给分!

hurt75 2004-07-08 11:20:32
如何得到4位的随机整数?谢谢给分!
...全文
194 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
jinsfree 2004-07-08
  • 打赏
  • 举报
回复
楼上两位的应该可以解决问题了
hbwjz 2004-07-08
  • 打赏
  • 举报
回复
public String generateRandom(){
String fourRandom = "";
int randomNum = (int)(Math.random()*10000);
fourRandom = "" + randomNum;
int randLength = fourRandom.length();
if(randLength<4){
for(int i=1; i<=4-randLength; i++)
fourRandom = "0" + fourRandom;
}else{
fourRandom = "" + randomNum;
}
return fourRandom;
}
hl_longman 2004-07-08
  • 打赏
  • 举报
回复
random
public static double random()
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.
When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression

new java.util.Random
This new pseudorandom-number generator is used thereafter for all calls to this method and is used nowhere else.
This method is properly synchronized to allow correct use by more than one thread. However, if many threads need to generate pseudorandom numbers at a great rate, it may reduce contention for each thread to have its own pseudorandom-number generator.


Returns:
a pseudorandom double greater than or equal to 0.0 and less than 1.0.
See Also:
Random.nextDouble()


用他产生一个0-1的数,再*1000就成了一个四位的,可能还要取一下整吧!

62,623

社区成员

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

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