"Book"객체를 노드로 유지하는 Graph를 구현하고 있습니다. 책이 키워드를 공유하면 노드가 연결됩니다. 각 도서의 키워드는 Book 클래스의 Vector에 보관됩니다. 이를 위해 3 개의 클래스를 만들었습니다.잘못된 Vector.size()가 반환되었습니다.
1) 책 2) 정점 3) 그래프
정점 클래스는 예약 개체를 보유하고 있으며 또한 다른 모든 정점 오브젝트 (키워드를 공유하는 다른 책을)를 포함하는 벡터를 가지고있다. 드라이버에서 나는 책을 만들어 Graph에 전달한 다음 Vertex에, 마지막으로 Vertex를 "bookGraph"라는 Vector에 삽입합니다.
public final class Graph {
private Vector<Vertex> bookGraph = new Vector<Vertex>();
private int bookCounter = 0;
public Graph() {
}
public void addBook(Book bk) {
Vertex vtx = new Vertex(bk);
bookGraph.add(vtx);
bookCounter++;
System.out.println("Book #1 has " + bookGraph.get(0).getBook().getKeywords().size() + " keywords");
// addAdjVertices();
}
public void showKeywords() {
System.out.println("Book #1 is " + bookGraph.get(0).getBook().getKeywords().size() + " keywords");
}
책의 정보는 드라이버의 파일에서 읽혀 책 객체에 삽입됩니다. 나는이 정보가 그래프에 정확하고 올바르게 삽입되어 읽히도록 노력하고 있습니다. 내 문제는 그래프 클래스의 "showKeywords()"메서드 내에서 키워드 Vector의 크기를 가져 오려고 할 때 발생합니다. getBookwords() .get (0) .getBook(). getKeywords(). size()는 addBook() 메서드의 똑같은 명령이 올바른 크기를 반환 할 때 0을 반환합니다. Book 클래스에서 getTitle() 또는 getAuthor()와 같은 접근 자 메서드를 구현했으며 showKeywords() 메서드 내에서 제대로 작동합니다. 키워드 벡터는 showKeywords() 메소드 내 유일한 문제 인 것 같습니다. 여기서 내가 뭘 잘못하고 있니?
여기에 작동해야처럼
boolean fileopen = false;
String title, author, keys;
long isbn_number;
Vector<String> keywords = new Vector<String>();
String filename = "books.txt";
String[] keywordTokens;
Scanner fin = null;
Scanner input = new Scanner (System.in);
Graph books = new Graph();
try {
fin = new Scanner (new FileReader(filename));
String fline;
fileopen = true;
System.out.println("Reading books.txt...");
while (fin.hasNextLine()) {
fline = fin.nextLine();
title = fline;
fline = fin.nextLine();
author = fline;
fline = fin.nextLine();
isbn_number = Long.parseLong(fline);
fline = fin.nextLine();
keywordTokens = fline.split(",");
for (int x = 0; x < keywordTokens.length; x++) {
keywords.add(keywordTokens[x]);
}
Book tempBook = new Book(title,author,isbn_number,keywords);
books.addBook(tempBook);
keywords.clear();
if (fin.hasNextLine()) fline = fin.nextLine();
}
books.showKeywords();
System.out.println("Ready.");
}
catch (FileNotFoundException e) {
System.out.println("FILE NOT FOUND!");
}
귀하의 질문에 대한 대답이 아니지만 ArrayList 사용을 고려하십시오 – Bozho
처음에 강사가 제안한 벡터가 있지만 결국 그 선택을 남겨 둡니다. 나는 그의 제안을하기로 결심했다. ArrayList는 어떤 이점을 제공합니까? 감사. – Vaheh
ArrayList가 동기화되지 않기 때문에 조금 더 잘 수행됩니다. 또한 더 많은 인터페이스를 구현하므로 더 편리하게 사용할 수 있습니다. –