zoukankan      html  css  js  c++  java
  • java--递归

    一、递归的概述

      递归,指在当前方法内调用自己的这种现象。递归分为两种,直接递归和间接递归。直接递归称为方法自身调用自己。间接递归可以A方法调用B方法,B方法调用C方法,C方法调用A方法。

    二、递归打印所有子目录中的文件路径

     1 //获取某目录下所有的文件
     2 public class Demo03 {
     3     public static void main(String[] args) {
     4         File file=new File("e:\test");
     5         getAllFile(file);
     6     }
     7     public static void getAllFile(File file){
     8         //获取该目录下的文件及文件夹
     9         File[] files=file.listFiles();
    10         //遍历该目录下的文件及文件夹里的文件
    11         for(File f:files){
    12             if(f.isDirectory()){
    13                 System.out.println(f+"文件夹下有以下文件:");
    14                 getAllFile(f);
    15             }else{
    16                 System.out.println(f);
    17             }
    18         }
    19     }
    20  }

    三、搜索指定目录中的.java文件(含子目录)

    自定义类继承FileFilter过滤器

    public class YourFilter implements FileFilter{
        public boolean accept(File pathname) {
            // TODO Auto-generated method stub
            //如果是文件夹,则不进行过滤,认为满足条件加到File数组中
            if(pathname.isDirectory()){
                return true;
            }else{
                return pathname.getName().toLowerCase().endsWith(".java");
            }
        }
    }

    测试类

    public class Demo05 {
        public static void main(String[] args) {
            File file=new File("e:\test");
             getAllFile(file);
        }
        //获取目录及子目录的java文件
        public static void getAllFile(File file){
            File[] files=file.listFiles(new YourFilter());
            for(File f:files){
                if(f.isDirectory()){
                    getAllFile(f);
                }else{
                    System.out.println(f);
                }
            }
        }
    }

    例子:

    用递归运算1-100之和

    public class Demo04 {
        //递归:要运行的方法主体不变,而参与运行的方法参数会变
        //递归必须要写一个程序的出口,否则该程序没有意义
        public static void main(String[] args) {
            getNum(100);
        }
        //计算1-100的和
        public static int getNum(int n){
            if(n==1){
                return 1;
            }else{
                return n+getNum(n-1);
            }
        }
    }
  • 相关阅读:
    搭建wamp环境,数据库基础知识
    练习题:选择器和选择好友
    例子:滑动效果
    TCPDump
    内存
    Cache和Buffer的区别(转载)
    经典问题回忆
    history
    DNS
    bc的用法
  • 原文地址:https://www.cnblogs.com/-dashu/p/9506489.html
Copyright © 2011-2022 走看看