我在调用方法时遇到问题。该程序的基础是从data.txt中读取数据,获取给定的名称令牌,然后获取所有后续的成绩,然后对成绩进行一些操作以给出该人成绩的详细信息。我在一个名为 Grades.java 的单独文件中执行所有方法,该文件具有 Grades 类。我只是遇到了麻烦,因为我的代码中必须有 testGrades 方法(我认为没有必要)。我已经完成了我需要做的一切,以使结果在不同的程序中变得完美,而没有两个不同的 .java 文件。但有必要这样做。我想我几乎已经确定了所有内容,我只是对如何实现和调用 testGrades 方法感到困惑。我将其注释掉,并对它在程序中的位置提出疑问。对类和对象以及一般的 java 来说相当新。对不起这个蹩脚的问题。
public class Lab2 {
public static void main(String[] args) {
Scanner in = null; //initialize scanner
ArrayList<Integer> gradeList = new ArrayList<Integer>(); //initialize gradeList
//grab data from data.txt
try {
in = new Scanner(new File("data.txt"));
} catch (FileNotFoundException exception) {
System.err.println("failed to open data.txt");
System.exit(1);
}
//while loop to grab tokens from data
while (in.hasNext()) {
String studentName = in.next(); //name is the first token
while (in.hasNextInt()) { //while loop to grab all integer tokens after name
int grade = in.nextInt(); //grade is next integer token
gradeList.add(grade); //adding every grade to gradeList
}
//grab all grades in gradeList and put them in an array to work with
int[] sgrades = new int[gradeList.size()];
for (int index = 0; index < gradeList.size(); index++) {
sgrades[index] = gradeList.get(index); //grade in gradeList put into grades array
}
//testGrades(sgrades); How would I implement this method call?
}
}
public static void testGrades(Grades grades) {
System.out.println(grades.toString());
System.out.printf("\tName: %s\n", grades.getName());
System.out.printf("\tLength: %d\n", grades.length());
System.out.printf("\tAverage: %.2f\n", grades.average());
System.out.printf("\tMedian: %.1f\n", grades.median());
System.out.printf("\tMaximum: %d\n", grades.maximum());
System.out.printf("\tMininum: %d\n", grades.minimum());
}
}
这是 Grades.java 文件开头的小片段
public class Grades {
private String studentName; // name of student Grades represents
private int[] grades; // array of student grades
public Grades(String name, int[] sgrades) {
studentName = name; // initialize courseName
grades = sgrades; // store grades
}
public String getName() {
return studentName;
} // end method getName
public int length() {
return grades.length;
}