返回一个由 n 个随机数组成的整数数组列表? [英] return an ArrayList of Integers that consist of n random numbers?
本文介绍了返回一个由 n 个随机数组成的整数数组列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何创建方法 RandomArray 并让它接受一个整数 n 并返回一个由 0 到 255 之间的 n 个随机数组成的整数 ArrayList.(换句话说:让返回的数组的大小为 n)???(我正在使用 Java Eclipse)我已经创建了 RandomArray,但是我不知道如何将它放在 ArrayList 中,这是我到目前为止所得到的:
How do I create the method RandomArray and let it take in an integer n and return an ArrayList of Integers that consist of n random numbers between 0 and 255.(in other words: let the returned array be of size n)??? (I am using Java Eclipse) I have created the RandomArray, however I do not know how to put it in an ArrayList, this is what I've got so far:
import java.util.Random;
public class Lab6 {
public static void main(String[] args) {
Random random = new Random();
int[] n = new int[1];
for( int i = 0 ; i < n.length ; i++ ) {
for ( int i1 = 0 ; i1 < n.length ; i1++ ) {
n[i1] = random.nextInt(255);
}
}
for( int a : n ) {
System.out.println( a );
}
}
}
推荐答案
你的意思是这样的:
public ArrayList<Integer> randomArrayList(int n)
{
ArrayList<Integer> list = new ArrayList<>();
Random random = new Random();
for (int i = 0; i < n; i++)
{
list.add(random.nextInt(255));
}
return list;
}
这篇关于返回一个由 n 个随机数组成的整数数组列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文