[英]Why isn't my for loop adding more than one random value to my list?
I'm trying to create a bubble sort algorithm in java and I'm trying to create a list with random integers in it with a for loop, however it only ever has one value. 我试图在Java中创建一个冒泡排序算法,并且试图通过for循环在其中创建一个包含随机整数的列表,但是它只有一个值。 This is the code: 这是代码:
public class bubbleSort {
public static void main(String[] args)
{
int length = getLength();
System.out.println(length);
List<Integer> randomList = createArray(length);
System.out.println(randomList);
}
public static int getLength()
{
System.out.println("Please enter how long you want the array to be");
Scanner reader = new Scanner(System.in);
int length = Integer.parseInt(reader.nextLine());
return length;
}
public static List<Integer> createArray(int length)
{
Random rand = new Random();
List<Integer> randomList = new ArrayList<Integer>();
for(int x = 0 ; x < (length + 1) ; x++);
{
int randomnumber = rand.nextInt((100 - 1) + 1) + 1;
randomList.add(randomnumber);
}
return randomList;
}
}
public static List<Integer> createArray(int length)
{
Random rand = new Random();
List<Integer> randomList = new ArrayList<Integer>();
for(int x = 0 ; x < (length + 1) ; x++)
{
int randomnumber = rand.nextInt((100 - 1) + 1) + 1;
randomList.add(randomnumber);
}
return randomList;
}
Your problem is here. 您的问题在这里。
You should only create a single Random instance that you use to generate your random numbers. 您应该只创建一个用于生成随机数的随机实例。
This is because the random numbers are from a seed value, and when you don't provide a seed for the random number number generator generator, it will be created with a seed value from epoch time, so all your numbers are the same because of this. 这是因为随机数来自种子值,并且当您不为随机数发生器生成器提供种子时,将使用纪元时间的种子值来创建它,因此由于这个。
A simple solution would be to update your createArray(int length)
to take a random instance, like so createArray(int length, Random random)
and use this instance to generate the numbers. 一个简单的解决方案是将您的createArray(int length)
更新为一个随机实例,例如createArray(int length, Random random)
并使用此实例生成数字。
There should be no semicolon (;) after your for loop declaration .That is why the loop keeps exiting after the first loop, It should be for循环声明后不应使用分号(;),这就是为什么循环在第一个循环后一直退出的原因,应该是
for(int x = 0 ; x < (length + 1) ; x++)
{
int randomnumber = rand.nextInt((100 - 1) + 1) + 1;
randomList.add(randomnumber);
}
And why do you have a (length +1)..if you want the size of the random list to be the size of the length ,you should remove the +1. 以及为什么要有(长度+1)..如果您希望随机列表的大小为长度的大小,则应删除+1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.