简体   繁体   中英

Using strings from a text file in a linked list/adjacency graph in java

Okay, my current code creates a list using integers, however I'd like it to use strings instead. The strings I want to use are in a text file called names.txt which reads like this:

Peter
Simon
Mark
Matthew
Paul
Luke

My code as follows:

import java.util.*;

class Graph1{
    class Edge{
         String v;
         public Edge(String v){
            this.v = v; 

        }

         public String toString(){
            return "(" + v + ")";
        }
    }
    List<Edge> G[];
    public Graph1(int n){
        G=new LinkedList[n];
        for(int i=0;i<G.length;i++)
            G[i]=new LinkedList<Edge>();
    }
    boolean isConnected(int u,String v){
        for(Edge i: G[u])
            if(i.v==v) return true;
        return false;
    }
    void addEdge(int u,String v){ 
        G[u].add( 0,new Edge(v) );  

    }

    public String toString(){
        String result="";
        for(int i=0;i<G.length;i++)
            result+=i+"=>"+G[i]+"\n";
        return result;
    }
}
public class GraphExample {
    public static void main(String[] args) {
        Graph1 g=new Graph1(6);
        g.addEdge(0, "Simon");
        g.addEdge(0, "Peter");
        g.addEdge(2, "Matthew");
        g.addEdge(9, "Mark");

        System.out.println(g);
        System.out.println(g.isConnected(1,"Peter"));
    }
}

This gives the output:

0=>[(Peter), (Simon)]
1=>[]
2=>[(Matthew)]
3=>[]
4=>[]
5=>[(Mark)]

false

However, instead of 0,1,2 etc, I want it to read Peter, Simon, Mark etc.

Thanks!

You have to read in the lines of the files:

List<String> lines = Files.readAllLines(Paths.get("names.txt"));

And make it available to your Graph. In the toString() use this list to get the name:

public String toString(){
    String result="";
    for(int i=0;i<G.length;i++)
        result+=lines.get(i)+"=>"+G[i]+"\n";
    return result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM