I am creating random number generator in Java as part of program I am writing to learn the language better (come from more C#/C++ background).
ArrayList<Integer> al = new ArrayList<Integer>();
Random ran = new Random();
for(int i = 1; i <= 11; i++)
al.add(i);
for(int i = 0; i < 2; i++)
{
ArrayList<Integer> temp = new ArrayList<Integer>();
int num = al.remove(ran.nextInt(al.size()));
temp.add(num);
Arrays.sort(temp);
text("\Random Number " + i + " is: " + temp[i]);
}
On arrays.sort(temp) I get a no suitable method error and in my text output function I get array required but java.util.ArrayList found. Can anyone suggest a better way to sort this random number array into ascending order or see something I am doing wrong currently that could easily be corrected? Thanks.
Use
Collections.sort(temp).In Java, arrays and lists are two different beasts.
Arrays.sort()only works for arrays; the equivalent function for lists isCollections.sort().I can’t say I fully understand the logic behind your code, but you might also want to take a look at
Collections.shuffle().edit Upon closer inspection, there are other problems with the code:
tempfrom scratch, so on each loop iteration it will contain exactly one element.temp[i]is not valid syntactically; the correct syntax istemp.get(i). Even with the correct syntax, it’ll give you an “out of bounds” exception, sincetemponly contains one element.