jeudi 27 août 2015

Java Finding Average with Loop and Arrays

This is a Java problem I am having, I am somewhat new to Java.

I have to:

  1. generate a random fraction

  2. keep generating until the sum is greater than 1

  3. then I have to display how many numbers I generated and which ones

Here is what I have so far in my function:

public static double calcAvg(int numOfTimes){
        double sumOfRand = 0 ;
        int numOffractions = 0;
        double avg = 0;

        double numOfAvg[] = new double[numOfTimes]; // number of rows
        double randNums[] = new double[] {.1,.2,.3,.4,.5,.6,.7,.8,.9};
        Random rand = new Random();


        for(int i = 0; sumOfRand <= 1; i++){
            int randNum = rand.nextInt(randNums.length); //gets a number from array randomly
                //System.out.println(randNums[randNum]);


            sumOfRand += randNums[randNum]; //adds it to the sum
              numOffractions++; //counts # of avgnums needed for > 1

              numOfAvg[i] = numOffractions; 

        }

        avg = (numOfAvg[0] + numOfAvg[1] + numOfAvg[2]) /(numOfTimes); 

    return avg;
}

I keep getting an error on: numOfAvg[i] = numOffractions; and I can't seem to add the fractions to the sum until they pass 1.




Aucun commentaire:

Enregistrer un commentaire