Java recursion: A NB masturbating operation

Source: Internet
Author: User

The core idea of recursion: calling itself by itself

Example one: factorial of 5

General Method:

Using the While loop

1 public class Demo01 {2  3 public      static void main (string[] args) {4          int result = Test (5); 5
      
       SYSTEM.OUT.PRINTLN ("result is" +
        } 7 8 public static int test (int num) {9 int result=1; Um>0) {result=result*num;12 num-- }14 return }16}       
      

Use recursion

1 public class Demo01 {2  3 public      static void main (string[] args) {4          int result = print (5); 5
      SYSTEM.OUT.PRINTLN ("result is" +     } 7       8 public      static int print (int num) {9 if (Num==1) {Ten return 1;}else {num*print (num-1 }15}        

Example two:

List A folder's descendants files and directories

1 public class Demo01 {2  3 public      static void main (string[] args) {4          file Dir=new file ("F:\\aa") ; 5          listfiles (dir, "|--"     } 7       8 public      static void listfiles (File dir, String space) {9 file[] fi Les = dir.listfiles (); Ten for(File file:files) {One-by-one (file.isfile ()) {System.out.println (space+  File.getname ());}else if(File.isdirectory ()) {listfiles (file, "|") + }18}          

Example three:

Delete a non-empty folder

1 public class Demo01 {2  3 public      static void main (string[] args) {4          file Dir=new file ("F:\\aa") c7/>     } 7       8 public      static void Deletedir (File dir) {9 file[] files = dir.listfiles ();//Lists All Filefile:files {//Files traversal query one by one if file.delete ();}else if }18} /c8>  

Java recursion: A NB masturbating operation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.