如何通过Java中的方法传递我的学生对象数组?

时间:2017-03-12 17:13:28

标签: java arrays object methods

我是Java的新手(1-2天),我想知道如何通过方法传递一组对象。当我编译代码时,我会收到" class,enum expected"或类似的东西。具体来说,我想阅读学生信息,然后通过另一种方法展示其信息。 附:很抱歉重复,但实际上我无法理解任何已回答的问题。

package javalearning;

import java.util.Scanner;

public void showStudents(int n) {
    for (i=0; i<n; i++) {
            System.out.println("Student #"+i+" has "+s[i].getAge()+" and he is in "+s[i].getStudy()+" year !");
    }
}

public class JavaLearning {

    public static void main(String[] args) {
      int i;
      String name;
      System.out.println("Insert number of students: ");
      Scanner n = new Scanner(System.in);
      int N = n.nextInt();
      for (i=0; i<N; i++) {
           Student[] s = new Student[N];
           s[i] = new Student();
           System.out.println("Age: ");
           Scanner _age = new Scanner(System.in);
           int AGE = _age.nextInt();
           System.out.println("Year of study: ");
           Scanner _year = new Scanner(System.in);
           int YEAR = _year.nextInt();
           s[i].setAge(AGE);
           s[i].setYearOfStudy(YEAR); 
      }
      showStudents(N);
    } 
}

以下是学生班:

package javalearning;

public class Student {
    public int age;
    public int yearOfStudy;

    public int getAge() {
        return age;
    }
    public void setAge(int _age) {
        this.age = _age;
    }
    public int getYearOfStudy() {
        return yearOfStudy;
    }
    public void setYearOfStudy(int y){
        this.yearOfStudy = y;
    }
}

2 个答案:

答案 0 :(得分:1)

要做的第一件事是移动showStudents内部类定义,然后再试一次。您无法在类定义之外定义方法。

答案 1 :(得分:0)

查看代码中的评论:

public class JavaLearning {

    public static void main(String[] args) {
        //code removed
    } 

    //method should be INSIDE the class 
    public static void showStudents(int n, Student[] s) { //path Student array
        int i;
        for (i=0; i<n; i++) {
                System.out.println("Student #"+i+" has "+s[i].getAge()+" and he is in "+s[i].getStudy()+" year !");
         }
    }
}