我的问题和这两个有点类似;
- 传递数组给Java方法,
- 如何在Java中传递数组和当前索引到方法
但是我遇到了一个问题,因为我只需要从一个方法中打印数组的数据。
下面是我的代码:public static void main(String[] args) {
Student[] s1 = {new Student("Karen", "male", 121, "N", 2, "e"),
new Student("K", "male", 122, "e", 3, "e"),
new Student("L", "male", 123, "", 4, ""),
new Student("M", "male", 124, "", 5, ""),
new Student("O", "female", 125, "", 1, "")};
s1.studentInfo(); //My questions involves something like this
}
设置如下
new Student(String StudentName, String Gender, int StudentNumber, String program, int YearLevel, String Orgs)
这是我希望数组数据可以访问的方法,然后打印它
public void studentInfo(){
System.out.println("Student name: "+super.getName());
System.out.println("Gender: "+super.getGender());
System.out.println("Student number: "+super.getStudNumber());
System.out.println("Program: "+getProgram());
System.out.println("Year Level: "+getYrlevel());
System.out.println("Organization: "+getOrg());
}
只需遍历数组并将元素传递给studentInfo
方法:
public static void main(String[] args) {
Student[] s1 = {new Student("Karen", "male", 121, "N", 2, "e"),
new Student("K", "male", 122, "e", 3, "e"),
new Student("L", "male", 123, "", 4, ""),
new Student("M", "male", 124, "", 5, ""),
new Student("O", "female", 125, "", 1, "")};
for(Student s : s1) {
studentInfo(s);
}
}
public static void studentInfo(Student s){
System.out.println("Student name: "+s.getName());
System.out.println("Gender: "+s.getGender());
System.out.println("Student number: "+s.getStudNumber());
System.out.println("Program: "+s.getProgram());
System.out.println("Year Level: "+s.getYrlevel());
System.out.println("Organization: "+s.getOrg());
}
首先定义如下方法
public void studentInfo(){
System.out.println("Student name: "+this.getName());
System.out.println("Gender: "+this.getGender());
System.out.println("Student number: "+this.getStudNumber());
System.out.println("Program: "+this.getProgram());
System.out.println("Year Level: "+this.getYrlevel());
System.out.println("Organization: "+this.getOrg());
}
在学生班。然后你可以在任何你需要的地方使用:
Stream.of(s1).forEach(Student::studentInfo)
其中s1为学生数组。
看起来你想要的是这样的:
private static void studentInfo(final Student[] students) {
for (final Student student : students) {
System.out.println("Student name: "+ student.getName());
System.out.println("Gender: "+ student.getGender());
System.out.println("Student number: "+ student.getStudNumber());
System.out.println("Program: "+ student.getProgram());
System.out.println("Year Level: "+ student.getYrlevel());
System.out.println("Organization: "+ student.getOrg());
}
}
你可以这样称呼它:
studentInfo(s1);
还要注意,根据Java命名约定,参数名应该以小写字母开头。