PDA

View Full Version : Looping the same function


vkidv
07-29-2007, 11:39 PM
Hi.

I want to loop one of 5 functions in a say, 100 times. I don't want to repeat the loop 5 times for each function - in the function code.
(These numbers are just theoretical)
I believe I can use overriding & extending a class.

Is there a cleaner way to do it?

In javascript, I would do:

function DoThat(What) {
for (var i=0; i < 100;i++)
What() ;
}


Unfortunately you cannot pass functions as references in Java.

In Java, I believe something like this could work:

public class Looper {
public void execute() {
for (int i = 0 ; i < 100 ; i++) {
doThing() ;
}
}
public void what() { }
}



// one of those 5 functions
public class SomeOther() extends Looper{
public void what() {
... // do stuff
}
}



public void main() {
SomeOther my = new SomeOther() ;
SomeOther.execute() ;
}


Is there a simpler way?

jkim
08-07-2007, 04:49 AM
The easiest way of doing this, abeit a work around, would be the following:


interface IFiveFunction
{
public static final int FOO1 = 1;
public void foo1();
public static final int FOO2 = 2;
public void foo2();
public static final int FOO3 = 3;
public void foo3();
public static final int FOO4 = 4;
public void foo4();
public static final int FOO5 = 5;
public void foo5();
public void foox(int x);
};

public class FiveFunction implements FiveFunction
{
public void foo1() { ... }
...
public void foo5() { ... }
};

public class Looper
{
...
public void loop()
{
... (select the function to be run and store it in x, i.e. int x = IFiveFunction.FOO1;)
IFiveFunction ff = new FiveFunction();
...
for (int i = 0; i < 100; i++) {
ff.foox(x);
}
...
}
...
};


Does this simplify it a bit?

There are more dynamic ways of doing it if I recall, but this is the simplest soluton I can think of without using stuff like java reflections.

Lallo
08-10-2007, 12:04 AM
function DoThat(What) {
for (var i=0; i < 100;i++)
DoThat(What) ;
}
You mean of recursion? Like this? :) This will loop the same function for X times until the condition is satisfied.

Let me know!

Regards!