【问题标题】:How do I assign string to vertex in for loop?如何在for循环中将字符串分配给顶点?
【发布时间】:2014-04-03 20:10:28
【问题描述】:

我正在尝试在 java 中实现 dijkstra 算法。我尝试在文本文件中获取节点名称。我在一个名为 []nodes

的数组中分配了节点名称

我使用以下代码在我的项目中手动添加顶点:

Vertex a = new Vertex("a");

我想用这个代码用 for 循环从文本文件中分配顶点名称

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

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

    }

但它给了我这个错误

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

我该如何解决这个问题?

【问题讨论】:

  • 强烈建议您发布更多代码。目前尚不清楚发布的代码试图做什么。

标签: java dijkstra vertex


【解决方案1】:

这不是有效的语法;您需要在 for 循环之外定义 Vertex 数组,并将文件的内容存储在其他地方,即

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]);
}

【讨论】:

    【解决方案2】:

    您目前正在尝试使用我认为是 String (nodes[i]) 的方式创建 Vertex

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

    但你的问题就在于此。您正在尝试将 Vertex 对象重新插入到 String 数组中。您需要一个用于 Vertex 对象的替代数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-08
      • 1970-01-01
      • 2021-09-03
      • 1970-01-01
      • 1970-01-01
      • 2016-01-12
      • 1970-01-01
      相关资源
      最近更新 更多