2014-04-20 48 views
0

所以我想返回扫描仪,专门文件

public static Scanner fileWriter() 
{ 
    Scanner sc = new Scanner(System.in); 
    System.out.println("What is the name of the file? (succeeded by .txt)"); 
    //String firs = sc.nextLine(); 
    try 
    { 
    Scanner scanner = new Scanner(new File("Test.txt")); 
    } 
    catch(IOException e) 
    { 
    System.out.println("Io exception" + e.getMessage()); 
    } 
    return scanner; 
} 

虽然这工作,我有问题的唯一的事情是“回归扫描仪”。

的错误是“无法找到符号”

return scanner; 
    ^

我在做什么错? !:(谢谢

+3

变量有*范围*。具体来说,就是封闭块。 –

回答

1

这条线:

Scanner scanner = new Scanner(new File("Test.txt")); 

是花括号内try block。因此,它只在那些大括号内可见。为确保它在外面可见,声明变量在try之前:

Scanner scanner; 

然后,在try块内,只需分配给它,不要声明它(区别在于你不包含类型名称;这使它成为一项转让声明):

scanner = new Scanner(new File("Test.txt")); 
+0

谢谢...为什么我的问题被低估了? – user3543629

0

scanner不是try块的范围之外可见你可以做,而不是执行以下操作:

public static Scanner fileWriter() 
{ 
    Scanner sc = new Scanner(System.in); 
    System.out.println("What is the name of the file? (succeeded by .txt)"); 
    String fileName = sc.nextLine(); 
    try 
    { 
     return new Scanner(new File(fileName)); 
    } 
    catch(IOException e) 
    { 
     System.out.println("Io exception" + e.getMessage()); 
    } 
    return null; 
}