返回一个由 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;
}