无法向邻接矩阵图添加顶点

t1rydlwq  于 2021-07-07  发布在  Java
关注(0)|答案(0)|浏览(259)

我在向邻接图添加新的顶点和边时遇到问题,因为当它尝试插入新的边时,它会说顶点不存在,因此返回false,因此不会添加。我正在读取文件并直接从文件中创建图形
这是我的课

public class Friendship {

    /**
     * Graph with the users and their relationships
     */
    private AdjacencyMatrixGraph<User, Relationship> friendshipGraph;

    /**
     * Map with the Users
     */
    private HashMap<String, User> users;

    /**
     * Constructor Friendship
     */
    public Friendship(){
        friendshipGraph = new AdjacencyMatrixGraph<>();
    }

    /**
     * Read files to create an AdjacencyMatrixGraph directly from the txt files
     *
     * @param usersFiles
     * @param relationshipFiles
     * @return
     */
    public AdjacencyMatrixGraph<User, Relationship> readFiles(String usersFiles, String relationshipFiles){
        users = new HashMap<>();
        BufferedReader br = null;
        FileReader fr = null;

        try{
            fr = new FileReader(usersFiles);
            br = new BufferedReader(fr);

            String sCurrentLine;

            while ((sCurrentLine = br.readLine()) != null) {
                String s[] = sCurrentLine.split(",");
                User newUser = new User(s[0], Integer.parseInt(s[1]), s[2]);
                users.put(s[0], newUser);
            }
            br.close();
            fr.close();

            fr = new FileReader(relationshipFiles);
            br = new BufferedReader(fr);

            while ((sCurrentLine = br.readLine()) != null) {
                String s[] = sCurrentLine.split(" ,");
                // verifica se ambos os users existem na lista
                if(users.containsKey(s[0])){
                    if(users.containsKey(s[1])){
                        Relationship newRelationship = new Relationship(users.get(s[0]), users.get(s[1]));
         // my problem is here
                        friendshipGraph.insertEdge(newRelationship.getUser1(), newRelationship.getUser2(), newRelationship);
                    }
                }
            }

        }catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return friendshipGraph;
    }

以及插入新边的方法

public boolean insertEdge(V vertexA, V vertexB, E newEdge) {

        if (vertexA.equals(vertexB)) {
            return false;
        }

        int indexA = toIndex(vertexA);
        if (indexA == -1) {
            return false;
        }

        int indexB = toIndex(vertexB);
        if (indexB == -1) {
            return false;
        }

        if (edgeMatrix[indexA][indexB] != null) {
            return false;
        }

        insertEdge(indexA, indexB, newEdge);

        return true;
    }

当我试着得到vertexa的指数时,它说它是-1,所以它不加。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题