老师让我们写一个搜索本地文件的小程序,我在写输入指定文件名的时候发现不知道如何输入一个全局变量。求大神指导!
import java.io.File;
import java.util.Scanner;
public class FindFile3 {
public static File path = new File("c:\\file");
public static String[] file = path.list();
public static int count = 0;
        public static String name=null;
public static void main(String[] args){
init();

run(file.length,file);
childpath(file,path);
System.out.println("--------The end----------");
}
public static void childpath(String[] k,File p ){
for(int i=0;i<k.length;i++){//循环遍历目录下所有文件
File childpath = new File(p+"\\"+k[i]);  //建立子目录
String[] childfile = childpath.list(); //返回该目录下所有文件的目录
if(childpath.isDirectory()){
run(childfile.length, childfile);
path = childpath;
file = childfile;
childpath(file,path);
}
}
}
public static void run(int len,String[] Str){

for(int i=0;i<len;i++){
if(Str[i].indexOf(name)!=-1)
System.out.println(Str[i]);
System.out.println(name);
}
}
private static void init(){
System.out.println("请输入要查找的文件");
Scanner sc = new Scanner(System.in);
String names = sc.next();
name = names;
}

}

解决方案 »

  1.   

    public static int count = 0; 就是全局的
      

  2.   

    字符串连接 是这个意思嘛  "path"+全局变量
      

  3.   

    你的那几个public static 变量都是“全局”的,对于这个类来说。
    事实上你应该尽量避免使用“全局”变量,刚开始你就当是一个好习惯,后来会慢慢知道原因的。如果不用比如说"name"变量,你让init()方法返回一个String,而这个String就是name的值。同样的,run方法中的name引用也可以通过添加一个参数给run而传入。