我正在创建一个使用 2 个类的程序。在一个类中,我创建了由第二个类调用的方法。所有方法都包含在第一个类中,第二个类简单地调用它们并执行代码。
1级
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Student {
private Scanner scanner;
private String firstName;
private String lastName;
private int homeworkScore;
private int testScore;
private String letterGrade;
private int numberOfStudents;
public Student () {
String firstName = null;
String lastName = null;
int homeworkScore = 0;
int testScore = 0;
String letterGrade = null;
int numberOfStudents = 0;
}
public void openFile(){
try {
scanner = new Scanner(new File("grades.txt"));
} catch (FileNotFoundException e) {
System.out.println("Error opening file. Please make sure that you have a grades.txt file in the same folder as GradeCalculator.class");
System.exit(0);
}
}
public void setNumberOfStudents() {
System.out.println("It kinda works");
numberOfStudents = scanner.nextInt();
}
public void setFastName() {
fastName = scanner.next();
}
public void setLastName() {
lastName = scanner.next();
}
public void setHomeworkScore() {
int subAssignment = 0;
int assignment = 0;
for(int i = 1; i <= 21; i++) {
subAssignment = scanner.nextInt();
assignment += subAssignment;
}
homeworkScore = assignment;
}
2 级
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class CourseGrade {
public static void main(String[] args) {
Student myStudent = new Student();
myStudent.openFile();
myStudent.setNumberOfStudents();
myStudent.setFirstName();
myStudent.setLastName();
myStudent.setHomeworkScore();
}
}
这是我得到的错误:
It kinda works
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Student.setHomeworkScore(Student.java:54)
at CourseGrade.main(CourseGrade.java:20)
...“它有点工作”语句只是为了查看它是否正确调用了该方法,看起来就是这样。
据我了解,该错误告诉我它正在从 .txt 文件中读取错误的类型,但不知道为什么会这样。它甚至可以正确读取文件吗?任何类型的帮助都会很棒,因为我已经盯着这段代码看了好几个小时了!