使用对象数组调用构造函数

问题描述 投票:0回答:4

我需要创建一个对象数组,并从控制台中读取构造函数中元素的值。我完全很困惑如何去做。任何人都可以明确如何做到这一点

public class Student {
    int id;
    String name;
    double marks;

    public Student(int id, String name, double marks) {
        id = this.id;
        name = this.name;
        marks = this.marks;
    }
}

public class Solution {
    public static void main(String[],args)
    {
      Scanner sc = new Scanner(System.in);
      int n=sc.nextInt();
      Student[] arr=new Student[n];
      for(int i=0;i<n;i++)
      {
         int x =sc.nextInt();
         String y=sc.nextLine();
         double z=sc.nextDouble();
         arr[i]=arr.Student(x,y,z);
      }
    }
}

我对如何调用构造函数感到困惑。谁能帮我?

java
4个回答
1
投票

你可以做以下两件事之一:

1.通过调用构造函数然后在数组中添加该对象来创建临时对象:

Student temp= new Student(x,y,z);
arr[i]=temp;

2.直接实例化一个新对象并将其添加到数组中,如下所示:

arr[i]=new Student(x,y,z);

这两种方法都可以正常工作,但是建议使用方法2,因为如果没有这样做,你就不应该为temp对象分配内存了。


1
投票

代替:

ARR [I] = arr.Student(X,Y,Z);

做:

arr [i] =新学生(x,y,z);

为什么?因为,数组中的每个对象都是Student类的实例


1
投票

你的构造函数被错误地声明了。 this始终用于引用实例变量。将构造函数更改为:

public class Student {
int id;
String name;
double marks;

public Student(int id, String name, double marks) {
    this.id = id;
    this.name = name;
    this.marks = marks;
} }

public class Solution {
    public static void main(String[],args)
    {
      Scanner sc = new Scanner(System.in);
      int n=sc.nextInt();
      Student[] arr=new Student[n];
      for(int i=0;i<n;i++)
      {
         int x =sc.nextInt();
         String y=sc.nextLine();
         double z=sc.nextDouble();
         arr[i]= new Student(x,y,z); //no need to create an object for arr
      }
    }
}

-1
投票

因为你的构造函数是错误的。

public class Student {
    int id;
    String name;
    double marks;

    public Student(int id, String name, double marks) {
        this.id = id;
        this.name = name;
        this.marks = marks;
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.