我想從一個已經傳入一個集合的對象輸出一個字符串。下面這行是我的問題所在。它輸出[alex,jane]但格式正確,我相信它應該在alex jane輸出。即沒有逗號分隔值和數組中的括號。嘗試從一個對象傳入一個集合輸出一個字符串
System.out.print(module.getStudents() + " ");
我已經嘗試了各種解決方案,包括:
System.out.prinf(%s, module.getStudents() + " ");
和
System.out.prinln(module.getStudents().[whatever Netbeans makes available] + " ");
爲了幫助你更好地理解這個問題。到目前爲止,該應用程序的想法是讓用戶搜索一個mosule並返回所有連接到它的學生。完整的源代碼欄上的驅動程序是:
import java.util.*;
public class Control {
public void run() {
Student jane = new Student("jane");
Student alex = new Student("alex");
Set<Student> students = new HashSet<Student>();
students.add(jane);
students.add(alex);
Module ufce1 = new Module("UFCE1");
Module ufce2 = new Module("UFCE2");
Set<Module> modules = new HashSet<Module>();
modules.add(ufce1);
modules.add(ufce2);
jane.addModule(ufce1);
jane.addModule(ufce2);
alex.addModule(ufce2);
ufce1.addStudent(jane);
ufce2.addStudent(jane);
ufce2.addStudent(alex);
System.out.println("Search module code: ");
Scanner scan = new Scanner(System.in);
scan = new Scanner(System.in);
String searchModule = scan.nextLine().trim();
for (Module module : modules) {
if (searchModule.equalsIgnoreCase(module.getName())) {
Iterator it = students.iterator();
Student student = (Student) it.next();
if (student.getModules().contains(module)) {
System.out.print(student + " ");
}
}
}
}
}
模塊類:
import java.util.HashSet;
import java.util.Set;
public class Module {
private String name;
private Set<Student> students = new HashSet<Student>();
public Module(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void addStudent(Student student){
students.add(student);
}
public Set<Student> getStudents() {
return students;
}
@Override
public String toString() {
return name;
}
}
學生類別:
import java.util.HashSet;
import java.util.Set;
public class Student {
private String name;
private Set<Module> modules = new HashSet<Module>();
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void addModule(Module module){
modules.add(module);
}
public Set<Module> getModules() {
return modules;
}
@Override
public String toString() {
return name;
}
}
我已經添加了一個迭代器的代碼。這就是你的建議。這將打印出所有學生,無論他們是否在該模塊上 – newToJava
是的,因爲您沒有進行任何過濾。你需要做的是:'學生student = it.next(); if(student.getModules()。contains(module)){System.out.print(student +「」);}' – Chris
@ Chris謝謝。但是當我之前添加這個:Iterator it = students.iterator();它說不兼容的類型? – newToJava