我正在开发一个简单的应用程序,它根据特定模块返回学生分数。我的主要问题是 getModuleMark
方法,因为我需要它返回给定模块索引的模块标记。
对于 setModuleMark
方法,我已经传递了索引模块和标记参数。我只是对需要在模块标记的返回中放入什么内容感到有点困惑。
当我运行应用程序时,我得到以下输出:
Joe Bloggs
Module 0: 50.0
Module 1: 50.0
Module 7: 50.0
参见下面的代码:
public class Student {
public static void main(String[] args) {
Student student = new Student("Joe", "Bloggs");
// Add some marks to the student.
student.setModuleMark(0, 10);
student.setModuleMark(1, 80);
student.setModuleMark(7, 50);
// Display the marks.
System.out.println(student.getForename() + " " + student.getSurname());
System.out.println("Module 0: " + student.getModuleMark(0));
System.out.println("Module 1: " + student.getModuleMark(1));
System.out.println("Module 7: " + student.getModuleMark(7));
}
private String forename;
private String surname;
private double marks;
public Student(String forename, String surname) {
super();
this.forename = forename;
this.surname = surname;
double [] ModuleMark = new double [7]; //Creates array of fixed size 7
}
/**
* @return the forename
*/
public String getForename() {
return this.forename;
}
/**
* @return the surname
*/
public String getSurname() {
return this.surname;
}
/**
* @param marks the marks to set
* @param i
*/
public double getModuleMark (int in) {
return this.marks;
}
public void setModuleMark(int in, double marks) {
this.marks = marks;
}
}
最佳答案
有很多事情似乎是错误的。
首先,ModuleMark
应在类中声明,而不是在构造函数中声明。
private double[] ModuleMark; // Declare here
public MyMain(String forename, String surname) {
this.forename = forename;
this.surname = surname;
this.ModuleMark = new double[7]; // Creates array of fixed size 7
}
接下来,您的 getModuleMarks 和 setModuleMarks 方法需要像这样
public double getModuleMark(int in) {
return this.ModuleMark[in]; // return the value present at the given index
}
public void setModuleMark(int in, double marks) {
this.ModuleMark[in] = marks; // set the marks at the given index in the array.
}
此外,由于 ModuleMark
是一个大小为 7 的数组,因此您不能使用索引 7。它会抛出 ArrayIndexOutOfBoundsException ,因为在数组中,最大可能的可访问索引始终为 array.length - 1
。
student.setModuleMark(6, 50); // The max possible index
...
System.out.println("Module 7: " + student.getModuleMark(6)); // The max possible index
注意:进行这些更改后,私有(private)双标记;
将不再使用。如果您将来打算将其用于其他目的,您可以丢弃它或保留它。
关于Java返回数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19617073/