我正在使用Java进行编码挑战,其中我的司机从文本文件中读取城市名称及其之间的里程。然后,此信息将传递给将填充加权的无向图的方法。城市名称是节点,它们之间的里程是权重。我正在编写Graph类,并且正在使用邻接表的链接列表数据类型。
import java.util.LinkedList;
public class WeightedGraph {
static class Edge
{
String origin;
String destination;
int weight;
public Edge(String origin, String destination, int weight)
{
this.origin = origin;
this.destination = destination;
this.weight = weight;
}
}
static class Graph
{
int numVertices;
LinkedList<Edge>[] adjList;
Graph(int numVertices)
{
this.numVertices = numVertices;
adjList = new LinkedList[numVertices];
for(int i = 0; i < numVertices; i++)
{
adjList[i] = new LinkedList<>();
}
}
}
public void addUndirectedEdge(String origin, String destination, int weight)
{
Edge edge = new Edge(origin, destination, weight);
adjList[origin].add(edge);
adjList[destination].add(edge);
}
}
在我正在处理的示例中,节点被编号而不是命名,并且变量“ origin”和“ destination”是整数。有人建议我需要获取字符串的索引值并在各行中使用它们:
adjList[origin].add(edge);
adjList[destination].add(edge);
位于addUndirectedEdge方法中。我怎么做? 我需要将变量“ origin”和“ domain”声明为整数而不是字符串吗?
答案 0 :(得分:0)
adjList[origin].add(edge);
adjList[destination].add(edge);
来源和目的地在这里是字符串。而且您正在尝试按字符串获取数组项。
答案 1 :(得分:0)
以您的IDE语言:
预期:adjList[int]
发现:adjList[String]