我是Java的初学者,我需要帮助。我只想从文本文件中获取值,然后将这些值与Object的变量进行比较。但不知何故,它以错误的方式运作。我花了超过4-5个小时而陷入困境。这是我的代码。
private List<Course> hs = new ArrayList<>();
private List<String> list = new ArrayList<>();
private String[] properties;
public void readLines() {
try (BufferedReader br = Files.newBufferedReader(Paths.get(Instructor.root.toString()), StandardCharsets.UTF_8)) {
list = br.lines().collect(Collectors.toList());
for(int i = 0; i < list.size(); i++) {
properties = list.get(i).split("%");
Course course = new Course(properties[0]);
Undergraduate undergraduate = new Undergraduate(properties[0],properties[1], properties[2], properties[3]);
if(hs.size() != 0 && isObjectInSet(course, hs)) {
getIfObjectInSet(course, hs).setUndergraduates(undergraduate);
}else {
course.setUndergraduates(undergraduate);
hs.add(course);
}}
}catch (IOException e) {
System.err.println(e);
}
//System.out.println(hs.size());
}
public boolean isObjectInSet(Course object, List<Course> hs) {
boolean result = false;
for (int i = 0; i < hs.size(); i++) {
String arrayedCourse = hs.get(i).getCourseID();
String objectsID = object.getCourseID();
if (objectsID.equals(arrayedCourse)) {
result = true;
break;
}
}return result; }
public Course getIfObjectInSet(Course object, List<Course> set) {
Course result = null;
for (int i = 0; i < set.size(); i++) {
if (isObjectInSet(object, set)) {
result = set.get(i);
break;
} }return result;
}}
这是课程类'变量:
public class Course {
private String courseID;
private ArrayList<Undergraduate> undergraduates = new ArrayList<>();
课程班级中的setUndergraduates
public void setUndergraduates(Undergraduate undergraduates) {
ArrayList<Undergraduate> students = this.undergraduates;
students.add(undergraduates);
this.undergraduates = students;
}
这是文本文件结构
BIM101%11111111111%帕帕%25
这是调试。两个字符串相等但它告诉它们不是
答案 0 :(得分:1)
请在您的班级Course
中覆盖方法declare
,方法是添加要比较的字段。 Hint
答案 1 :(得分:0)
我认为问题出在您的getIfObjectInSet()
中 - 它使用isObjectInSet()
,但如果任何元素匹配,则返回true,而不是仅仅当前元素匹配。
无论如何,你最好在这里使用Map - 你可以完全避免这两个功能:
private Map<String, Course> courses = new TreeMap<>();
public void readLines(Path file) {
try (BufferedReader br = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
br.lines().forEach(line -> {
String[] parts = line.split("%");
String courseId = parts[0];
Undergraduate undergraduate = new Undergraduate(courseId, parts[1], parts[2], parts[3]);
Course course = courses.get(courseId);
if (course == null) {
course = new Course(courseId);
courses.put(courseId, course);
}
course.setUndergraduates(undergraduate); // rename to addUndergraduate?
});
} catch (IOException e) {
throw new RuntimeException(e); // don't just continue on errors..
}
}