我的问题是:
创建一个包含学生姓名、学籍号码、地址、电子邮件和电话的班级学生。从main方法中,为批处理创建一个Student对象数组,并打印它。注意,main应该在不同的类中。
我创建了两个学生对象,但我不知道如何将其添加到数组中。
public class Student {
String name;
int rollNum;
String address;
String email;
int phoneNum;
}
public class TestClass {
public static void main(String[] args){
Student[] student=new Student[2];
Student student1=new Student();
Student student2=new Student();
student1.name="Pooja";
student1.rollNum=9164086;
student1.address="Chennai";
student1.email="poojasingh@gmail.com";
student1.phoneNum=232732;
student2.name="Smriti";
student2.rollNum=9159999;
student2.address="Lucknow";
student2.email="angel.smriti@gmail.com";
student2.phoneNum=232735;
student[0]=student1;
student[1]=student2;
System.out.print("{");
for(int i=0;i<student.length;i++){
if(i>0){
System.out.print(",");
}
System.out.print(student[i]);
}
System.out.print("}");
}
}发布于 2014-05-22 17:59:28
您已经在数组中添加了student1和student2,问题是除非对象重写方法:toString,否则无法打印对象。但只需这样做:
System.out.println(student[i].name + ", " + student[i].rollNum + ", " + student[i].address + ", " + student[i].email + ", " + student[i].phoneNum);并从for循环中删除if (i>0) {...}。
或者,如果您想重写toString,只需将这段代码添加到Student类中:
@Override
public String toString() {
return name + ", " + rollNum + ", " + address + ", " + email + ", " + phoneNum;
}在主要用途方面:
for(int i = 0; i < student.lenght; i++) {
System.out.println(student[i]);
}发布于 2014-05-22 17:47:31
您已经将Student对象添加到数组student中。如果问题是没有得到预期的输出,原因是因为它们是对象,所以必须重写Student类中的Student方法:
@Override
public String toString() {
return name; // for example
}您应该返回一个String,它显示有关对象的相关信息。上面的方法只是一个例子,所以您可能想要更改它。
https://stackoverflow.com/questions/23813787
复制相似问题