Java 使用学生对象初始化数组的每个元素

Java 使用学生对象初始化数组的每个元素,java,arrays,eclipse,object,Java,Arrays,Eclipse,Object,我创建了一个具有名称和其他属性的Student类。但是现在我想用Student对象初始化数组的每个元素。这个代码对吗?月食抛出许多红点。 帮助。您从未定义过setName方法,因此我假设这就是您出现编译器错误的原因。像这样的东西应该在学生课堂上起作用 public class Student { int marks; String name; char sex; String email; } Student[] s = new Student[10];

我创建了一个具有名称和其他属性的Student类。但是现在我想用Student对象初始化数组的每个元素。这个代码对吗?月食抛出许多红点。
帮助。

您从未定义过setName方法,因此我假设这就是您出现编译器错误的原因。像这样的东西应该在学生课堂上起作用

public class Student { 
    int marks; 
    String name; 
    char sex; 
    String email; 
}
Student[] s = new Student[10];

public class StudentDemo {
    Student s[] = new Student[10];// array Student//
    Student s1  = new Student();//  Student Object//
    s1.setName("John"); //Eclipse says here there is a mistake an ask to delete John// 
    Student[0]=s1;
}
试试这个。 代码中的问题:

您在函数之外编写了函数逻辑。更正在我的 使用main方法编写代码。 一个类文件中不能有2个公共类。所以我把学生档案设为非公开的。 您没有学生名称属性的setter。
使用您创建的数组的引用,而不是数组的类型
因此,将Student[0]替换为s[0]

您的代码有很多错误

应该是

 class Student { 
    int marks; 
    String name; 
    char sex; 
    String email;
    public void setName(String string)
    {
        // TODO Auto-generated method stub

    } 
}


public class StudentDemo{
    public static void main(String [] args)
    {
    Student s[] = new Student[10];// array Student//
    Student s1  = new Student();//  Student Object//
    s1.setName("John"); //Eclipse says here there is a mistake an ask to delete John// 
    s[0]=s1;
    }
}
您还需要在方法中编写代码。像这样:

 Student[] s = new Student[10];
 s[0] = new Student();
 s[0].setName();
请注意,我使用了一个事实,即在位置0处有一个Student对象,然后我只设置了名称。没有真正的理由使用s1。

以下几点:

首先,您的第一个数组应该这样编写:

 public void doStuffHere()
 {
     // Code goes here.
 }
Student[] s = new Student[10];
其次,您从未在学生类中定义过方法setNameString名称。这看起来像这样:

 public void doStuffHere()
 {
     // Code goes here.
 }
Student[] s = new Student[10];
除此之外,您不能只调用类中的方法,它需要进入方法、构造函数或初始化块内部

例如:

public void setName(String name)
{
    this.name = name;
}
这可以帮助你

public class StudentDemo
{
    Student[] studentArray = initStudentArray();

    private Student[] initStudentArray()
    {
        Student[] ret = new Student[10];
        Student s = new Student();
        s.setName("John");
        ret[0] = s;

        ...

        return ret;
    }
}

您需要在某个方法中编写此代码。不能直接在类内部编写逻辑。请使用s[0]=s1;而不是学生[0]=s1;。我定义了所有的setter和getter