我有一些代码,我想打印出其中有学生的所有班级清单。我希望此列表按class_id排序,并且我希望每个不同的类之间都有一个空格。例如:
100 Math Jon Doe
100 Math Tina Lee
100 Math Sally
122 Science Tom Edison
122 Science Jon Frankin
现在,代码可以正确打印了,除了没有空格分隔各类。
我知道错误在这里:
while(!"class_id".equals("class_id")) {
System.out.println("\n");
}
只是不确定我在做什么错。
static void listAllClasses() {
System.out.println("\nClasses With Enrollment\n");
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ClassSelector?autoReconnect=true&useSSL=false", "", "");
String totalEnroll = ("SELECT * FROM ClassSelector.student_x_class ORDER BY class_id");
myStmt = con.prepareStatement(totalEnroll);
rs = myStmt.executeQuery(totalEnroll);
while (rs.next()) {
String totalEnrollment = rs.getString("class_id") + "\t" + rs.getString("class_name") + "\t" + rs.getString("student_id") + "\t" + rs.getString("student_name");
while(!"class_id".equals("class_id")) {
System.out.println("\n");
}
System.out.println(totalEnrollment);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
最佳答案
尝试这个 :
static void listAllClasses() {
String currentClassId ="";
String oldClassId = "";
System.out.println("\nClasses With Enrollment\n");
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ClassSelector?autoReconnect=true&useSSL=false", "", "");
String totalEnroll = ("SELECT * FROM ClassSelector.student_x_class ORDER BY class_id");
myStmt = con.prepareStatement(totalEnroll);
rs = myStmt.executeQuery(totalEnroll);
while (rs.next()) {
currentClassId = rs.getString("class_id");
String totalEnrollment = rs.getString("class_id") + "\t" + rs.getString("class_name") + "\t" + rs.getString("student_id") + "\t" + rs.getString("student_name");
while(currentClassId != null && oldClassId != null && !currentClassId.equals(oldClassId)) {
System.out.println("\n");
}
oldClassId = currentClassId;
System.out.println(totalEnrollment);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
关于java - 在Java输出中插入空行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36088483/