How can I execute a Java method more than once?
I need to run my/an Objects method a second time. Is this allow开发者_如何学编程ed? How can I do this?
Not sure what you are trying to do, but you can simply call a method from itself (it's called recursion):
void recursiveMethod() {
System.out.println("Called the recursive method");
recursiveMethod();
}
Calling that method will print the line "Called the recursive method" until you get a StackOverflowError.
You can call the method again from inside itself (AKA recursion). So, something like this:
public void myMethod() {
// Do some stuff here.
// Possible conditional statement...
if(restart) {
myMethod(); // This will "restart" the method.
}
}
If you have a more specific example that you're thinking of, that may help improve your question.
I guess you want to use recursion.
recursion? of course java supports it
public int foo (int param) {
if (param == 0)
return 0;
return param + foo (--param);
}
public static void main (String[] args) {
System.out.println (foo (5));
}
Seeing as you have a reference to the object (you already ran the method), Simply repeat the previous statement:
myDog.bark(); // bark once
myDog.bark(); // bark again
精彩评论