简体   繁体   中英

How do I assign string to vertex in for loop?

I'm trying to impelement dijkstra algorithm in java. I try to get node names in a text file. I assigned node names in an array called []nodes

I add vertex in my project manually with this code:

Vertex a = new Vertex("a");

I want to assing vertex names from text file with a for loop with this code

for(int i=0; i< numOfNodes; i++){

        Vertex nodes[i] = new Vertex(nodes[i]);

    }

but it gives me this error

Multiple markers at this line
- The constructor Vertex(Vertex) is undefined
- Type mismatch: cannot convert from Vertex to 
 Vertex[]
- Syntax error on token "i", delete this token

how can I solve this problem?

This isn't valid syntax; you need to define your Vertex array outside your for loop, and have the contents of the file stored somewhere else, ie

String text_input[] = new String[num_lines_in_file];
// Read the text file and store inputs in above array...
// ...

Vertex nodes[] = new Vertex[text_input.length];
for(int i=0; i< nodes.length; i++){
    nodes[i] = new Vertex(text_input[i]);
}

You're currently trying to create a Vertex with what I assume is a String ( nodes[i] )

Vertex nodes[i] = new Vertex(nodes[i]);

But there in lies your problem. You're trying to insert a Vertex object back into the String array. You need an alternative array for Vertex objects.

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