有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

关于try/catch和访问try中的元素的java帮助

try {
    inFile = new Scanner(file);
}
catch (FileNotFoundException e) {
    System.out.println("FileNotFoundException");
}

我有这个密码。但是,在try/catch语句之后,我有以下内容:

while(inFile.hasNext()) {
}

编译器告诉我我还没有初始化infle。我是否需要将所有代码都放在try/catch中?我做错了什么


共 (6) 个答案

  1. # 1 楼答案

    是的,你知道。如果引发异常,运行时将打印“FileNotFoundException”,并将继续运行,尽管尚未初始化内嵌

    当遇到此异常时,您应该使程序返回,或者仅当您确定程序已正确初始化时,才对infile执行操作

  2. # 2 楼答案

    如果遇到编译器错误,可能需要将inFile初始化为null

    请注意,在以后的代码中,您不应该假设infle不是null,您应该始终检查它:

    例如

    if (inFile != null) {
        while (inFile.hasNext()) {
            ...
        }
    }
    
  3. # 3 楼答案

    编译器正在抱怨,因为如果new Scanner()抛出FileNotFoundExceptioninFile将无法初始化(顺便说一句,非常不幸的变量名)。循环应该位于try块内,这也将增加可读性

    try {
        Scanner inFile = new Scanner(file);
        while(inFile.hasNext()) {
            //...
        }
        inFile.close();
    }
    catch (FileNotFoundException e) {
        System.out.println("FileNotFoundException");
    }
    
  4. # 4 楼答案

    try块与while循环不在同一范围内。将while循环放在try块中

  5. # 5 楼答案

    初始化填充:

    Scanner inFile = null;
    

    编辑:

    正如其他人所提到的,您应该小心,您可能会在while循环中获得NullPointerException。您应该考虑将while循环移动到TIE块中:

    Scanner inFile = null;
    ...
    try {
        inFile = new Scanner(file);
        while(inFile.hasNext()) {
        }    
    }
    catch (FileNotFoundException e) {
        System.out.println("FileNotFoundException");
    }
    
  6. # 6 楼答案

    出现警告的原因是,您应该首先将扫描仪设置为null。但是,您还应该将while循环移动到try块中,因为如果抛出异常,您不希望执行该while循环(因为infle将为null)