我在 Student
类中有一个 getSubjects
方法,该方法在子类中被重写。
我正在尝试使用 getSubjects
方法打印数组。
主要类代码为:
package javalab5;
import java.util.*;
/**
*
* @author Saj
*/
public class JavaLab5 {
public static final int DEBUG = 0;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Student s[] = new Student[10];
s[0] = new MathStudent(14,15);
s[1] = new MathStudent(16,19);
s[2] = new MathStudent(18,21);
s[3] = new MathStudent(23,28);
s[4] = new ScienceStudent(32,25);
s[5] = new ScienceStudent(28,56);
s[6] = new ScienceStudent(29,28);
s[7] = new ComputerStudent(25,38);
s[8] = new ComputerStudent(34,39);
s[9] = new ComputerStudent(45,56);
int numberOfStudents = 0;
for (int loop = 0; loop < numberOfStudents; loop++) {
System.out.print("Student "+ loop + " >>");
System.out.println(s[loop].getSubjects());
}
}
}
更新
这是 getSubjects
方法:
public String getSubjects(){
return(" Science Student >> " + "Physics Grade: " + physicsGrade
+ " Astronomy Grade: " + astronomyGrade);
}
最佳答案
首先,你的循环永远不会运行,因为这一行: int numberOfStudents = 0;
转换为英语,它的意思是:“只要 numberOfStudents 小于 0 就运行这个循环”但是你已经是 0 并且不小于 0!如果您尝试遍历整个数组,则应将其设置为 10,因为您有 10 个学生:
for (int loop = 0; loop < 10; loop++) {
System.out.print("Student "+ loop + " >>");
System.out.println(s[loop].getSubjects());
}
这应该有效:)
编辑:顺便说一句,我在这里使用的“10”是我们在工业中所谓的“魔数(Magic Number)”,基本上是一个未分配给变量的硬编码数字,想象一下,如果您有 10 个带有魔数(Magic Number)的循环,如果需要的话,您将不得不花费不必要的时间来更改所有这些,这通常是避免魔数(Magic Number)的最佳实践:
private final int NO_STUDENTS = 10;
Students[] s = new Students[NO_STUDENTS];
//populate your array here
//Now run loop
for (int loop = 0; loop < s.length; loop++) {
System.out.print("Student "+ loop + " >>");
System.out.println(s[loop].getSubjects());
}
关于java - 从数组打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42793963/