In general you can generate an array of random size:
java.util.Random rand = new java.util.Random();
final int MAX_SIZE = 100;
double[] a = new double[1 + rand.nextInt(MAX_SIZE)];
(Here I'm assuming you will not want arrays larger than 100 elements.)
Then you fill the array with random positive numbers:
for (int i = 0; i < a.length; ++ i)
{
a[i] = rand.nextDouble();
}
Then you normalize the array (divide each element by the total sum).
First we compute the total sum:
double sum = 0.0;
for (int i = 0; i < a.length; ++ i)
{
sum += a[i];
}
Then divide each array element by the sum:
for (int i = 0; i < a.length; ++ i)
{
a[i] /= sum;
}
If you want shorter code, you can combine the loop that accumulates the sum with the loop that fills the array with random positive integers. Here is the resulting code:
java.util.Random rand = new java.util.Random();
final int MAX_SIZE = 100;
double[] a = new double[1 + rand.nextInt(MAX_SIZE)];
double sum = 0.0;
for (int i = 0; i < a.length; ++ i)
{
a[i] = rand.nextDouble();
sum += a[i];
}
for (int i = 0; i < a.length; ++ i)
{
a[i] /= sum;
}