繁体   English   中英

使用try / catch后出现空指针异常

[英]Null pointer exception after using try/catch

仍在从事同一个程序。 我虽然在另一个线程的建议中几乎完成了我实现的try / catch语句,但效果很好,但是我现在在SimpleJavaAssignment.Company.main(Company的.java:31)”

触发异常的代码:

File file = new File(Company.class.getResource("input.txt").getFile());

完整的代码:

package SimpleJavaAssignment;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

public class Company
{
  ArrayList<Department> deptList = new ArrayList<Department>();

  public Department checkDepartment(String name)
  {
    for(Department dept: deptList)
    {
      if(dept.getName().equals(name))
      {
      return dept;
      }
    }
    Department d = new Department(name);
    deptList.add(d);
    return d;
  }

  public static void main(String[] args)
  {

    System.out.println ("This program will compile and display the stored employee data.");

    Scanner inputFile = null;
    File file = new File(Company.class.getResource("input.txt").getFile());


    try {

        inputFile = new Scanner(file);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Company c = new Company();
    String input = inputFile.nextLine();



    while(inputFile.hasNextLine() && input.length() != 0)
    {

      String[] inputArray = input.split(" ");
      Department d = c.checkDepartment(inputArray[3]);
      d.newEmployee(Integer.parseInt(inputArray[2]), inputArray[0] + " " + inputArray[1], d);
      input = inputFile.nextLine();
    }

    System.out.printf("%-15s %-15s %-15s %-15s %n", "DEPARTMENT", "EMPLOYEE NAME", "EMPLOYEE AGE",
          "IS THE AGE A PRIME");
    for(Department dept:c.deptList)
    {
      ArrayList<Employee> empList = dept.getEmployees();
      for(Employee emp: empList)
      {
      emp.printInfo();
      }
    }
  }    
}

调用Company.class.getResource("input.txt")

您正在使用相对资源名称, 相对资源名称是相对于类的包而言的。 因此,您确定在与SimpleJavaAssignment包相同级别的文件中存在一个名为input.txt的文件吗?

您也可以只指定文件的绝对路径,然后将其传递到File构造函数中,如下所示:

File file = new File("/my/path/input.txt");

暂无
暂无

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

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