【问题标题】:variable might not been initialized from Scanner?变量可能没有从扫描仪初始化?
【发布时间】:2015-05-01 08:24:39
【问题描述】:

我在try-exception 之前声明了Scanner infile,但由于某种原因它说变量可能没有被初始化?

Scanner infile;
        try 
        {
            infile = new Scanner(file);
        }
        catch(FileNotFoundException f)
        {
            System.out.println("Wrong File Path");
        }

        while (infile.hasNext())
        {
           System.out.print("Testing While loop");

【问题讨论】:

    标签: java while-loop try-catch java.util.scanner


    【解决方案1】:

    考虑如果在new Scanner 构造函数调用中抛出异常会发生什么。构造函数永远不会完成,因此new Scanner(file) 不会产生值;那么infile呢?

    要更正它,请将您的 while 循环移动 try 块:

    Scanner infile;
    try 
    {
        infile = new Scanner(file);
    
        while (infile.hasNext())
        {
           System.out.print("Testing While loop");
        }
    }
    catch(FileNotFoundException f)
    {
        System.out.println("Wrong File Path");
    }
    

    毕竟,异常处理的目的是让它远离你的主要逻辑。

    【讨论】:

    • 但最后我会使用构造函数。将while 循环移入内部并在try 内部声明构造函数会导致很多错误和更复杂的编程。正确的 ? @T.J.克劳德
    • @DkgMarine: 不。通过将try 放在所有您的逻辑并在最后处理异常,您可以让事情不那么复杂,不多。但你确实有一个选择:如果你不想把你的逻辑放在try中(这是最佳实践),你可以在catch块中设置infile = null,然后将循环更改为while (infile != null && infile.hasNext()) .但同样,不是最佳实践。您可能会发现 Java tutorial on exceptions 很有用。
    【解决方案2】:

    想象一下infile = new Scanner(file); 抛出异常的情况。在while (infile.hasNext()) 处,infile 不会被初始化。

    您只需将Scanner infile; 更改为Scanner infile = null; 即可解决此问题。但请注意,如果抛出上述异常,此时infile 仍然可以为空。您应该将这部分代码放在try 块中。

    【讨论】:

      【解决方案3】:

      解决此问题的最佳方法是使用 Java 内置的类错误处理。

      public static void main(String[] args) {
          Scanner infile;
          try {
              infile = new Scanner(new File("filename.txt"));
          } catch (FileNotFoundException f) {
              System.out.println("Wrong File Path");
          }
      
          while (infile.hasNext()) {
              System.out.print("Testing While loop");
          }
      }
      

      这段代码不会编译,因为有可能找不到文件,错误没有处理,但是如果你在主函数声明中添加throws FileNotFoundException,异常将由主函数处理并不会造成任何问题。

      public static void main(String[] args) throws FileNotFoundException{
          Scanner infile;
          infile = new Scanner(new File("filename.txt"));
          
          while (infile.hasNext()) {
              System.out.print("Testing While loop");
          }
      }
      

      对不起,如果我的解释不是很好,我自己只是从 Java 开始。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-30
        • 2021-04-01
        • 1970-01-01
        • 2016-02-24
        • 1970-01-01
        • 2012-03-25
        • 2015-07-04
        相关资源
        最近更新 更多