gpt4 book ai didi

java - toString(); java

转载 作者:行者123 更新时间:2023-12-02 00:01:53 24 4
gpt4 key购买 nike

谁能明白为什么我的 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:27‌​2)

最佳答案

NullPointerException 在这里。private int[] 数字;

您的实例中的 number 为 null。

当你调用grade.toString()时,该方法调用

 public static double averageMark(int [] numbers){
int sum = 0;
double average = 0.000;
for (int i = 0; i < numbers.length; i++){ // !!!! numbers is null

关于java - toString(); java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14688881/

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