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

时间:2012-11-22 02:29:15

标签: java try-catch

我尝试在try-catch块之后声明s.next(),但它不起作用!如果s位于try块内,则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 只会有下拉列表。

我不想将Parsing输入丢弃,对try块采取适当的操作,因为它们不会抛出FNFE和IOE。我能在这做什么?

{{1}}

3 个答案:

答案 0 :(得分:2)

我认为你的意思是你想使用 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.

答案 1 :(得分:1)

因为作为s类实例的Scanner变量仅限于try块。如果您希望s可以在<{em>} try-catch块之外访问,请在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);
    }

答案 2 :(得分:1)

在Java中,变量的作用域是声明它们的块。由于您的扫描程序是在try块内部构建的,因此在它之外是不可见的。

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

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

将自动关闭扫描程序资源。实际上,您可能会泄漏它,因为您的代码示例中没有finally块。

相关问题