编写一个方法来生成并返回用户指定大小的int数组中的一组随机值。值应该都在+/- N之间,其中N是常数,例如100。 谢谢。 这是我的;
import java.util.*;
public class Test
{
public static void main(String[] args)
{
int limit, numbers;
Random random = new Random();
Scanner scan = new Scanner(System.in);
System.out.print ("Enter your limit value for your array: "); //Needs to be positive.
limit = scan.nextInt();
int[] list = new int[limit];
for (int i = 0; i < list.length; i++)
{
System.out.print(list[i] + ", ");
}
numbers = random.nextInt(limit - (0 - limit)) + (0 - limit);
System.out.println (numbers);
System.out.println (list[numbers]);
}
}
答案 0 :(得分:0)
public List<Integer> random(int range, int count){
List<Integer> result = new ArrayList<Integer>();
for(int i=0;i<count;i++){
if(Math.random() > 0.5){
//adding positive value with probability of 0.5
result.add((int)(Math.random() * (double)range));
}else{
//adding negative value with probability of 0.5
result.add(-1 * (int)(Math.random() * (double)range));
}
}
return result;
}
如果要创建自己的随机数生成器,最容易实现的是线性同余生成器。从wiki阅读并试一试。在这里询问您是否需要帮助。