繁体   English   中英

扫描程序变量在try-catch块之外不起作用

[英]Scanner variable doesn't work outside the try-catch block

我试图在try-catch块之后声明s.next() ,但是它不起作用! 如果s在try块内,则只有下拉菜单。

我不想将解析输入混为一谈,将所有适当的操作全部放入try块,因为它们不会抛出FNFE和IOE。 我在这里可以做什么?

public static void main(String[] args) 
      {
        // TODO Auto-generated method stub

        //Open file; file name specified in args (command line)
        try{
            FileReader freader = new FileReader(args[0]);
            Scanner s = new Scanner(freader);

        }catch(FileNotFoundException e){
            System.err.println("Error: File not found. Exiting program...");
            e.printStackTrace();
            System.exit(-1);
        }catch(IOException e){
            System.err.println ("Error: IO exception. Exiting...");
            e.printStackTrace();
            System.exit(-1);
        }
        // if i try to declare s.next() here it would not work

我认为您的意思是您想使用 s.next(),但它不起作用。

为此,请将s声明为try / catch块外部的变量,然后将其设置为null。 然后将其分配在您现在分配的位置,但不带声明。 如果我的假设正确,那么您的问题是s不再是try / catch之外的活动变量,因为它是在该块中声明的。

FileReader freader = null;
Scanner    s       = null;
try { freader = new FileReader(args[0]); // risk null pointer exception here
      s = new Scanner(freader);
    }
catch { // etc.

因为作为Scanner类实例的s变量仅限于try块。 如果希望在try-catch之外可以访问s ,请在try-catch之外声明它。

 Scanner s = null;
 try{
        FileReader freader = new FileReader(args[0]);
         s = new Scanner(freader);

    }catch(FileNotFoundException e){
        System.err.println("Error: File not found. Exiting program...");
        e.printStackTrace();
        System.exit(-1);
    }catch(IOException e){
        System.err.println ("Error: IO exception. Exiting...");
        e.printStackTrace();
        System.exit(-1);
    }

在Java中,变量受声明它们的块限制。由于Scanner是在try块内部构造的,因此在它的外部不可见。

您是否有任何理由要在此块之外进行实际的扫描操​​作? 在Java 7中,一个常见的习惯用法是try-with-resources模式:

try (Scanner s = new Scanner(new FileInputStream(file)) {
  //Do stuff...
}

它将自动关闭扫描仪资源。 照原样,您可能会泄漏它,因为代码示例中没有finally块。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM