Adz
Adz

Reputation: 2847

How to recall a method n amount of times?

trying to recall a method here (so that it generates different results 100 times using a for loop)

Here is what I have in the main method:

for (int i = 0; i<99; i++) { 
            double scaleFitness = ScalesSolution.ScalesFitness(randomNumberFile);
            System.out.print(scaleFitness + ", ");
        }

and this is the method I'm trying to call 100 times (in the ScalesSolution class):

public static double ScalesFitness(ArrayList<Double> weights)
    {
        int n = scasol.length();
        double lhs = 0.0, rhs = 0.0;
        if (n > weights.size()) return(-1);

        for(int i = 0; i < n; i++){
            if(scasol.charAt(i) == '0'){
                lhs += weights.get(i);
            }
            else if (scasol.charAt(i) == '1') {
                rhs += weights.get(i);
            }
        }
        return(Math.abs(lhs-rhs));  
    }

This however prints the same value 100 time over.

Upvotes: 0

Views: 346

Answers (2)

elToro
elToro

Reputation: 1022

Your method "ScaleFitness" and the output of this method is dependent on two variables:

  1. weights

  2. scasol

It seems these variables stay the same for the whole run of the program. So it is not surprising that your output is the same.

If you want a different output for each run of your loop. You need to reset at least one of these variables to a new value.

Btw. methods in Java always start with a lowercase. Classes start with an uppercase.

Upvotes: 3

La-comadreja
La-comadreja

Reputation: 5755

public static double scalesFitness(ArrayList<Double> weights)
{
    double randomElement = weights[((int) (Math.random() * weights.size()))];

This will enable you to retrieve a random element in the array, for manipulation later.

Upvotes: 0

Related Questions