Primitive数据类型的数组可以初始化为:
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)...}
答案 0 :(得分:2)
假设有这样的构造函数Student(String, int)
,那么你可以试试这个:
Student[] studentArray = {
new Student("Sam", 21),
new Student("Jules",3)
};
答案 1 :(得分:1)
Student s[] = {new Student("Sam", 21), new Student("Jules", 3)}
答案 2 :(得分:0)
您可以通过以下方式简单地初始化自定义数据类型的数组:
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
}