谁能看到为什么我的toString()
方法不起作用?它编译得很好,但是当我运行它时出现运行时错误:
这是我的代码:
import java.util.*;
public class ExamMarks {
// fields
private String moduleName;
private int moduleCode;
private int year;
private int[] numbers;
// methods
public static int highestMark(int[] numbers) {
int highest = numbers[numbers.length - 1];
int i = numbers[0];
for (i = 0; i < numbers.length - 1; i++) {
if (numbers[i] > numbers[i + 1]) {
highest = numbers[i];
}
}
return highest;
}
public static double averageMark(int[] numbers) {
int sum = 0;
double average = 0.000;
for (int i = 0; i < numbers.length; i++) {
sum = numbers[i] + sum;
average = sum / numbers.length;
}
return average;
}
// Constructor
public ExamMarks() {
moduleName = "Object Oriented Programming";
moduleCode = 5015;
year = 2013;
}
// toString
@Override
public String toString() {
String result = ("The title of this module is : " + moduleName
+ "The code number of this module is: " + moduleCode
+ "The year of the Exam is: " + year + "Array average = "
+ averageMark(numbers) + "Highest grade = " + highestMark(numbers));
return result;
}
// Tester
public static void main(String[] args) {
ExamMarks grade = new ExamMarks();
Scanner percentages = new Scanner(System.in);
int[] numbers = new int[20];
double x = averageMark(numbers);
System.out.println("Please enter 20 marks");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = percentages.nextInt();
}
System.out.println(grade);
}
}
这是我得到的错误
java.lang.NullPointerException at ExamMarks.averageMark(ExamMarks.java:26)
at ExamMarks.toString(ExamMarks.java:42)
at java.lang.String.valueOf(Unknown Source)
at java.io.PrintStream.println(Unknown Source)
at ExamMarks.main(ExamMarks.java:65)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)