Java 如何创建一个包含“n”个随机整数的数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28970799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 07:07:05  来源:igfitidea点击:

How to create a array with "n" random integers?

javaarraysrandomarraylistinteger

提问by Malinator

Create two IntegerArrayListscontaining n ?elements each where n?? will be taken from the user.

创建两个IntegerArrayLists包含 n 个 ? 元素的每个元素,其中 n?? 将从用户那里取走。

so basically if a user inputs '6' two arrays with 6 elements needs to be created. How would I do this?

所以基本上如果用户输入 '6' 需要创建两个具有 6 个元素的数组。我该怎么做?

This is what I have.. but its not even remotely correct.

这就是我所拥有的……但它甚至远不正确。

Scanner input= new Scanner(System.in);
    System.out.println("please enter a integer 'n' ");
    int x= input.nextInt();

    int[] a = { 1, 4, 9, 16 };
    int[] b = { 9, 7, 4, 9, 11 };

采纳答案by Razib

You can take input from the user by using a scanner like this -

您可以使用这样的扫描仪来获取用户的输入 -

Scanner input= new Scanner(System.in);
System.out.println("Enter the array size: ");
int n = input.nextInt(); 

After that you can call a function generateRandomArray()with the size nget from the user -

之后,您可以generateRandomArray()使用n用户提供的大小调用函数-

public List<Integer> generateRandomArray(int n){
    ArrayList<Integer> list = new ArrayList<Integer>(n);
    Random random = new Random();

    for (int i = 0; i < n; i++)
    {
        list.add(random.nextInt(1000));
    }
   return list;
}  

Here - random.nextInt(1000)will generate a random number from the range 0 to 1000. You can fix the range as you want.

这里 -random.nextInt(1000)将生成一个范围为 0 到 1000 的随机数。您可以根据需要修复范围。

Hope it will help.
Thanks a lot.

希望它会有所帮助。
非常感谢。

回答by Maxqueue

    int x = input.nextInt();

    int[] a = new int[x];
    int[] b = new int[x];

Then you can populate values however you need them

然后你可以填充你需要的值

回答by Danyal Sandeelo

Scanner input= new Scanner(System.in);
System.out.println("please enter a integer 'n' ");
int x= input.nextInt();

int[] a = new int[x];
int[] b = new int[x];

This is basically integer array not array list

这基本上是整数数组而不是数组列表

for array list you need to create it using

对于数组列表,您需要使用创建它

 List<Integer> integerList=new ArrayList<Integer>();

回答by apelsin

First create your ArrayList of Integers. Then you can add however many Integers as you'd like.

首先创建您的 ArrayList of Integers。然后您可以根据需要添加任意数量的整数。

ArrayList<Integer> ar = new ArrayList<Integer>();
ar.add(1);

回答by sparkyShorts

I won't duplicate what others have said, since it is sufficient, but perhaps understanding the difference between ArrayLists and Arrays will benefit you.

我不会重复其他人所说的,因为它已经足够了,但也许理解 ArrayLists 和 Arrays 之间的区别会让你受益。

ArrayList Documentation

ArrayList 文档

Array Documentation

数组文档

ArrayLists grow dynamically, while Arrays have a fixed size. You can find how to populate them by following the excellent answers provided by the others.

ArrayLists 动态增长,而 Arrays 有固定大小。您可以按照其他人提供的优秀答案找到如何填充它们。

回答by Schalk

Since 1.8

从 1.8

// Since, as per your question, you're using arrays even though
// you state you want ArrayLists, we will assume you know why you're
// doing so.
int[] a = new int[x];
int[] b = new int[x];
Random random = new Random();
IntUnaryOperator unaryOpInt = (p) -> random.nextInt(maxIntVal);
// populate array a with random numbers
Arrays.setAll(a, unaryOpInt); 
// populate array b with random numbers
Arrays.setAll(b, unaryOpInt); 
// Since, as per your question, you require ArrayLists, you can
// create ArrayLists from arrays a and b as follows.
// create an ArrayList from array a
ArrayList<Integer> aArrList = new ArrayList<>(IntStream.of(a).boxed().collect(Collectors.toList()));
// create an ArrayList from array b
ArrayList<Integer> bArrList = new ArrayList<>(IntStream.of(b).boxed().collect(Collectors.toList()));

That being said and done, I'd just keep it simple and use a loop to initialize to a random value and work my way around not having to use arrays if I'm going to require ArrayLists or vise versa.

话虽如此,但我只是保持简单,并使用循环来初始化为随机值,并且如果我需要 ArrayLists 或反之亦然,则不必使用数组。

回答by Ruslan López

For the sake of completeness since java-8you can

为了完整起见,自java-8以来,您可以

  1. Generate an int stream from the next int from a Random number Generator as a Supplier ()->r.nextInt()
  2. Limit the stream to your desired size
  3. Convert it to Array

    int[] randomIntsArray=IntStream.generate(r::nextInt).limit(size).toArray()

  1. 从作为供应商的随机数生成器的下一个 int 生成一个 int 流 ()->r.nextInt()
  2. 将流限制为您想要的大小
  3. 将其转换为数组

    int[] randomIntsArray=IntStream.generate(r::nextInt).limit(size).toArray()

回答by Andrei Ciobanu

You can use MockNeat(disclaimer I am the author):

您可以使用MockNeat(免责声明我是作者):

MockNeat mockNeat = MockNeat.threadLocal();
MockUnitInt intUnit = mockNeat.ints().range(0, 100);

int[] arr1 = intUnit.arrayPrimitive(100).val();
Integer[] arr2 = intUnit.array(100).val();
List<Integer> list1 = intUnit.list(100).val();
List<List<Integer>> list2 = intUnit.list(100).list(100).val();

The library makes it easy to describe a behaviour for generating arbitrary data, and then reuse this "behavior" and generate all kinds of structures with it.

该库可以很容易地描述生成任意数据的行为,然后重用这种“行为”并用它生成各种结构。

回答by Nishad

If you want to generate random integer array from an interval, here are the options

如果你想从一个区间生成随机整数数组,这里有选项

// generate 100 random number between 0 to 100 
int[]  randomIntsArray = IntStream.generate(() -> new Random().nextInt(100)).limit(100).toArray();
//generate 100 random number between 100 to 200
int[]  randomIntsArray = IntStream.generate(() -> new Random().nextInt(100) + 100).limit(100).toArray();