简体   繁体   English

将文件中的输入转换为 object 参考

[英]Casting input from file as object reference

What I'm wondering is, is there a way to read the file so that the strings 'vertex' and 'connected' can be cast as a reference to the Vertex objects outside the loop?我想知道的是,有没有办法读取文件,以便可以将字符串“顶点”和“连接”转换为对循环外顶点对象的引用? The Strings will share the same name as the file is read, with it progressing from at, so that isn't a problem.字符串将与读取的文件共享相同的名称,并且从 at 开始,所以这不是问题。 If this isn't possible, is there any other way to work around this?如果这是不可能的,有没有其他方法可以解决这个问题? Maybe by somehow creating a vertex object within the loop yet not overwriting it?也许通过某种方式在循环中创建一个顶点 object 但不覆盖它? I tried it but it would overwrite itself for each loop, as it would create a new Vertex with the same value each time.我试过了,但它会为每个循环覆盖自己,因为它每次都会创建一个具有相同值的新顶点。 Thanks in advance.提前致谢。

    public static void main(String[] args) throws FileNotFoundException {

    File file = new File("ass3.txt");

    Scanner scan = new Scanner(f);

    if (file.exists() == false) {
        System.out.println("File doesn't exist or could not be found.");
        System.exit(0);
    }

    int nVertices = scan.nextInt();
    int nEdges = scan.nextInt();

    for (int i = 0; i < 21; i++) {
        String s = scan.nextLine();
    }

    Queue selectedSet = new Queue();
    Queue candidateSet = new Queue();

    Vertex a = new Vertex("a");
    Vertex b = new Vertex("b");
    Vertex c = new Vertex("c");
    Vertex d = new Vertex("d");
    Vertex e = new Vertex("e");
    Vertex f = new Vertex("f");
    Vertex g = new Vertex("g");
    Vertex h = new Vertex("h");
    Vertex i = new Vertex("i");
    Vertex j = new Vertex("j");
    Vertex k = new Vertex("k");
    Vertex l = new Vertex("l");
    Vertex m = new Vertex("m");
    Vertex n = new Vertex("n");
    Vertex o = new Vertex("o");
    Vertex p = new Vertex("p");
    Vertex q = new Vertex("q");
    Vertex r = new Vertex("r");
    Vertex s = new Vertex("s");
    Vertex t = new Vertex("t");

    for (int z = 0; z < 99; z++) {

        String vertex = scan.next();
        String connected = scan.next();
        int weight = scan.nextInt();

        vertex.addNeighbour(new Edge(weight,vertex,connected));
    }

You should be using a Map .您应该使用Map This maps objects->objects, so in this case we would want it to be Strings->Vertex.这映射了 objects->objects,所以在这种情况下,我们希望它是 Strings->Vertex。

Some sample code:一些示例代码:

HashMap<String, Vertex> vertices = new HashMap<String, Vertex>();
vertices.put("a", new Vertex("a"));
...

You can then reference the map in or outside your loop然后,您可以在循环内部或外部引用 map

Vertex v = vertices.get(vertex);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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