【问题标题】:How can I pass my students array of objects through methods in Java?如何通过 Java 中的方法传递我的学生对象数组?
【发布时间】:2017-03-12 17:13:27
【问题描述】:

我是 Java 新手(1-2 天),我想知道如何通过方法传递对象数组。当我编译代码时,我收到“类,枚举预期”或类似的东西。具体来说,我想阅读学生的信息,然后通过另一种方法来炫耀它的信息。 附:抱歉重复,但我实际上无法从任何已回答的问题中理解。

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;
    }
}

【问题讨论】:

  • 1) showStudents 是任何类之外的方法......你不能那样做。 2) Student[] s = new Student[N]; 应该在外部任何循环
  • @Newbie1234 为什么?那是 Enum 类,这里不需要
  • @Newbie1234 我没有关注。具体做什么?

标签: java arrays object methods


【解决方案1】:

首先要做的是在类定义中移动你的showStudents,然后再试一次。您不能在类定义之外定义方法。

【讨论】:

    【解决方案2】:

    查看代码中的 cmets:

    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 !");
             }
        }
    }
    

    【讨论】:

    • (方法也需要是静态的)
    • 谢谢,我修好了。我的错误:是的,它需要是静态的才能从其他静态(即main)方法中引用
    • 我照你说的做了,但现在我在 getStudy() 处收到来自 showStudents() 方法的错误“找不到符号”
    猜你喜欢
    • 1970-01-01
    • 2011-05-11
    • 2023-03-03
    • 2015-02-16
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    相关资源
    最近更新 更多