我正在创建一个程序来显示已存储在数组中的类的名称,年龄和gpa。我使用构造函数,访问器和打印细节的方法创建了Student类。
在main方法中,我填充数组并希望显示数组中的所有项(这是我遇到的问题)。
这是我到目前为止所做的:
public class Student {
private String name;
private int age;
private double gpa;
public Student(String studentName, int studentAge, double studentGpa) {
this.name = studentName;
this.age = studentAge;
this.gpa = studentGpa;
}
//Normal accessors, not going to bother putting them on here.
public void printStudents() {
System.out.println("Name: " + name + ", Age: " + age + ", GPA: " + gpa);
}
//New class, imagine it's on a different file
public class MyClass {
private static Student [] students = new Student[3];
System.out.println("Students in my class");
students[0] = new Student("Mark",16,77.6);
students[1] = new Student("Sam",17,56.9);
students[2] = new Student("Polly",16,97.4);
for (int g = 0; g < students.length; g++) {
//This is where I'm stuck, I'm not sure how to call printStudents here. students.printStudents didn't work for some reason.
答案 0 :(得分:0)
class Student {
private String name;
private int age;
private double gpa;
public Student(String studentName, int studentAge, double studentGpa) {
this.name = studentName;
this.age = studentAge;
this.gpa = studentGpa;
}
public void printStudent() {
System.out.println("Name : "+this.name);
System.out.println("Age : "+this.age);
System.out.println("GPA : "+this.gpa);
}
}
public class MyClass {
public static void main(String s[])
{
Student [] students = new Student[3];
System.out.println("Students in my class");
students[0] = new Student("Mark",16,77.6);
students[1] = new Student("Sam",17,56.9);
students[2] = new Student("Polly",16,97.4);
for (int i = 0; i <=(students.length-1); i++) {
students[i].printStudent();
}
}
}
答案 1 :(得分:0)
正如@Hello_World在评论中提到的那样 - 将brew install phantomjs
方法名称更改为printStudents
以使其更有意义。它是printStudent
对象的公共方法,这意味着您可以直接从对象的实例访问它(例如Student
)。您还可以使用foreach循环遍历数组,这样更容易阅读。
students[0].printStudent()