有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何初始化包含1个以上成员变量的自定义数据类型数组?

基本数据类型的数组可以初始化为:

int a[] = {1 , 2, 3, 4, 5}; 

我创建了一个自定义数据类型,代码如下-

class Student
{
    private String name;
    private int rollno;
}

我创建了一个Student数组,如下所示:

Student s[] = new Student[5];
for(int i =0; i < s.length; s++)
    s[i] = new Student();

我想在不接受用户输入的情况下初始化成员变量:name和rollno。我该怎么做?我想做点像-

Student s[] = {("Sam", 21), ("Jules",3)...}

共 (2) 个答案

  1. # 1 楼答案

    只需通过以下方式初始化自定义数据类型的数组:

    
    class struct{
    int data;
    String str;
    }
    
    // while creating an array ...
    struct[] name = new struct[length];
    
    // for inserting data ..
    for( int i=0; i< length; i++){
       struct stk = new struct(); // create a new object to be stored..
       stk.str = "Priyansh Gupta from UPES Dehradun";   // declaring the values of the object we created
       stk.data = 2021;
       name[i] = stk;    // adding the object to the i'th index of array
    }
    
    // for printing the array
    for( int i=0; i<length; i++){
       System.out.println(name[i].data); // printing the data of i'th index of array
       System.out.println(name[i].str); // print the string value of the index
    }
    
  2. # 2 楼答案

    假设有这样的构造函数Student(String, int),那么您可以尝试以下方法:

    Student[] studentArray = {
        new Student("Sam", 21),
        new Student("Jules",3)
    };