我想打印所有学生对象'存储在ArrayList对象中的属性(name,subject,registrationNo)。
学生详细信息来自数据库并将其插入到学生对象中。 然后将这些学生对象插入到ArrayList中。
最后,我想逐个打印这些学生对象属性,如下所示。 以下是我的代码。
DBconn.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBconn {
static Connection conn;
public static Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/student_database", "root", "");
} catch (SQLException ex) {
}
} catch (ClassNotFoundException ex) {
}
return conn;
}
}
Student.java
public class Student {
private String name;
private String RegistrationNo;
private String course;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRegistrationNo() {
return RegistrationNo;
}
public void setRegistrationNo(String RegistrationNo) {
this.RegistrationNo = RegistrationNo;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
}
StudentList.java
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class StudentList {
public static ArrayList getStudentList() {
ArrayList list = new ArrayList();
String sql = "SELECT * FROM student";
try {
Statement stm = DBconn.getConnection().createStatement();
ResultSet rs = stm.executeQuery(sql);
while (rs.next()) {
Student student = new Student();
student.setName(rs.getString(1));
student.setCourse(rs.getString(2));
student.setRegistrationNo(rs.getString(3));
list.add(student);
}
} catch (SQLException ex) {
}
return list;
}
}
ViewStudent.java
public class ViewStudent {
public static void main(String[] args) {
int size = StudentList.getStudentList().size();
for (int i = 0; i < size; i++) {
System.out.println(StudentList.getStudentList().get(i));
//I want to get all student's name,subject and registrationNo
}
}
}
感谢。
答案 0 :(得分:3)
只需给学生一个public String toString()
方法覆盖,一个返回一个包含所有键属性的字符串,然后这将正常工作:
System.out.println(StudentList.getStudentList().get(i));
答案 1 :(得分:1)
您应该访问学生的属性并将其打印出来,而不是System.out.println(StudentList.getStudentList().get(i));
。
Student s = (Student) StudentList.getStudentList().get(i);
System.out.println(s.getName());
System.out.println(s.getCourse());
System.out.println(s.getRegistrationNo());