开发者

How can I execute a Java method more than once?

开发者 https://www.devze.com 2022-12-16 14:22 出处:网络
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 calledrecu

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号