gpt4 book ai didi

java - 未处理的异常类型 FileNotFoundException

转载 作者:太空宇宙 更新时间:2023-11-04 07:01:54 24 4
gpt4 key购买 nike

主类:

public class cfung58_lab03_Main {
//main class
//creates objects

//Unhandled Exception Type FileNotFoundException occurs on the line below
static cfung58_lab03_Department myDepartment = new cfung58_lab03_Department();

...
}

部门类别:

public class cfung58_lab03_Department {
....
static cfung58_lab03_Course[] coursesArray;
static cfung58_lab03_Student[] studentArray;

public cfung58_lab03_Department() throws FileNotFoundException{
File file = new File("Courses.txt"); //file for Courses.txt
//System.out.println(file.getCanonicalPath());//gets path
//File file2 = new File("Students.txt"); //file for Students.txt
//System.out.println("True or false: " + file.canRead());
if (file.exists()){
//if the course file exists

//load scanner object to read file course.txt string
//NOTE: remember to throw FileException
Scanner read = new Scanner(file);

//count the number of Courses first before
// creating the coursesArray and filling in the elements
int numberOfCourses = 0;

while (read.hasNext()){
//String courseName = read.next();
numberOfCourses++;
}

//create coursesArray
cfung58_lab03_Course[] coursesArray = new cfung58_lab03_Course[numberOfCourses];

//restart the scanner system for read
read = new Scanner(file);

while (read.hasNext()){
String courseName = read.next();

//for loop to fill in the elements for coursesArray
for (int i = 0 ; i < numberOfCourses ; i++){
//creating element
coursesArray[i] = new cfung58_lab03_Course(courseName, 0 );
}

}
}
//else throw exception
else
throw new FileNotFoundException("File could not be found.");

尽管我已经在部门构造函数上抛出了异常,但我不确定是什么导致了编译器错误。

Eclipse也没有解决方案。

知道是什么原因造成的吗?

最佳答案

您正在从名称可怕的主类中调用一个方法,并且该方法抛出一个已检查的异常。所以这个异常需要被捕获(或抛出,但你不能在这里抛出它,因为你正在从方法中分配静态变量):

static cfung58_lab03_Department myDepartment;

static {
try {
myDepartment = new cfung58_lab03_Department();
}
catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}

也就是说,这个字段可能应该是你的 main 方法的局部变量。

关于java - 未处理的异常类型 FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21981321/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com