返回由N个随机数的整数的ArrayList? [英] return an ArrayList of Integers that consist of n random numbers?
本文介绍了返回由N个随机数的整数的ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何创建方法RandomArray,让它参加一个整数n,并返回由0到255之间N个随机数的整数的ArrayList(换句话说:让返回的数组是大小n)? ??
(我使用Java的Eclipse)
我创建了RandomArray,但是我不知道如何把它放在一个ArrayList,这是我到目前为止有:
导入了java.util.Random;
公共类{六硼化镧 公共静态无效的主要(字串[] args){ 随机随机=新的随机();
INT [] N =新INT [1]; 的for(int i = 0; I< n.length;我++){
为(中间体I1 = 0; I1&下; n.length;的i1 ++){
N [I1] = random.nextInt(255);
}
}
对于(INT一:N){
的System.out.println(一);
}
}
}
解决方案
您的意思是这样的:
公开的ArrayList<整数GT; randomArrayList(INT N)
{
ArrayList的<整数GT;名单=新的ArrayList<>();
随机随机=新的随机(); 的for(int i = 0; I< N;我++)
{
list.add(random.nextInt(255));
}
返回列表;
}
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 );
}
}
}
解决方案
You mean something like this:
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个随机数的整数的ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文