我的代码问题是我有一个名为 Student 的类。此类计算学生的成绩并列出他们的姓名和成绩。第二类称为 CourseOffering,用于计算学期数、班级学生人数等。第三类是将所有内容放在一起。最重要的是,信息是从 .txt 文件中读取的。我测试了我的 Student 类,我得到的值是正确的,它工作正常,但是我尝试将 CourseOffering 类方法添加到等式中,我得到了这个错误......
Exception in thread "main" java.lang.NullPointerException
at CourseOffering.setNumberOfSemesters(CourseOffering.java:17)
at CourseStatistics.main(CourseStatistics.java:21)
学生类有读取 .txt 文件的代码,我不会包括其余部分,因为它并不重要......
public void openFile(){
try { //start try statement
scanner = new Scanner(new File("gradesA5.txt")); //initialize scanner to scan from the grades.txt file
} //end try statement
catch (FileNotFoundException e) { //start catch statement
System.out.println("Error opening file. Please make sure that you have a grades.txt file in the same folder as GradeCalculator.class"); //print statement telling user that the grades.txt file is not in the right place
System.exit(0); //system exit
} //end catch statement
}
CourseOffer课程...
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class CourseOffering {
private Scanner scanner;
//initialize data members
private int students;
private String description;
private int numberOfSemesters;
int studentArrayCount = 0;
public void setNumberOfSemesters(){
if(scanner.hasNext()){
numberOfSemesters = scanner.nextInt();
}
}
public int getNumberOfSemesters(){
return numberOfSemesters;
}
public void setStudents(){
int[] student = new int[numberOfSemesters];
student[studentArrayCount] = scanner.nextInt();
students = student[studentArrayCount];
studentArrayCount++;
}
public void computeHomeworkAverage(){
}
public void computeTestAverage(){
}
public void countPassingStudents(){
}
}
最后是调用方法的类......
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class CourseStatistics {
public static void main(String[] args) {
Student myStudent = new Student();
CourseOffering myCourse = new CourseOffering();
myStudent.openFile();
myCourse.setNumberOfSemesters();
myStudent.testing();
for(int i = 0; i < 4; i++){
myStudent.setfirstName();
myStudent.setLastName();
myStudent.setAssignmentScore();
myStudent.setLabScore();
myStudent.setMidterm1Score();
myStudent.setMidterm2Score();
myStudent.setFinalExamScore();
myStudent.setQuizScore();
myStudent.setAttendanceScore();
myStudent.setPATScore();
myStudent.setZyanteScore();
myStudent.computeLetterGrade();
System.out.println(myStudent.getFirstName() + " " + myStudent.getLastName() + " " + myStudent.computeTotalHomeworkScore() + " " + myStudent.computeTotalTestScore() + " " + myStudent.getLetterGrade());
}
System.out.println(myCourse.getNumberOfSemesters());
}
}
基本上我需要知道如何调用 CourseOffering 类,该类也假设是从 Student 类读取的 .txt 文件中读取,而不会出现错误。任何帮助,将不胜感激!!