try块后无法找到变量

时间:2015-10-31 22:29:56

标签: java exception exception-handling

我正在尝试处理用户输入的文件中的文本,当编译扫描仪时无法找到。我假设它被抓住了。我该怎么做才能使这项工作?

String namef = getf.nextLine();
File inPut = new File(namef);

try { 
    Scanner in = new Scanner(inPut);                            
}
catch (FileNotFoundException e) {
    System.out.println("file not found");
}

while(in.hasNextLine()) {  // process file
    String line = in.nextLine();
    String pLine = parse(count,  namef);
}

1 个答案:

答案 0 :(得分:2)

@Tom是对的。您必须在try块外声明扫描程序。

     String namef = getf.nextLine();
     Scanner in = new Scanner();  

     File inPut = new File(namef);                                    
     try
     { 
       in = new Scanner(inPut);  
       while(in.hasNextLine())       // process file
       {
         String line = in.nextLine();
         String pLine = parse(count,  namef);
       }                          
     }
     catch (FileNotFoundException e)
     {
       System.out.println("file not found");
     }