问题
I'm trying to put all random number which I generated to the arraylist and print all the random number into single array
static int pick;
public static void main(String[] args) {
ArrayList al = new ArrayList();
Random rand = new Random();
for (int j = 0; j<10; j++)
{
pick = rand.nextInt(100);
al.add(pick);
System.out.println("Contents of al: " + al);
}
from the above function I got the result like this
Contents of al: [43]
Contents of al: [43, 44]
Contents of al: [43, 44, 3]
Contents of al: [43, 44, 3, 66]
Contents of al: [43, 44, 3, 66, 47]
Contents of al: [43, 44, 3, 66, 47, 24]
Contents of al: [43, 44, 3, 66, 47, 24, 12]
Contents of al: [43, 44, 3, 66, 47, 24, 12, 35]
Contents of al: [43, 44, 3, 66, 47, 24, 12, 35, 0]
Contents of al: [43, 44, 3, 66, 47, 24, 12, 35, 0, 85]
the expected output I want is just the last line of the above result
Contents of al: [43, 44, 3, 66, 47, 24, 12, 35, 0, 85]
anyone know how to do it?
回答1:
If you want print the array when it is full take the println out of the loop.
Hope that answers your question
static int pick;
public static void main(String[] args) {
ArrayList al = new ArrayList();
Random rand = new Random();
for (int j = 0; j<10; j++)
{
pick = rand.nextInt(100);
al.add(pick);
}
System.out.println("Contents of al: " + al);
}
来源:https://stackoverflow.com/questions/14180419/put-random-number-in-the-array-list-java