mid*_*101 2 java scope compiler-errors
我正在实现广度优先和深度优先搜索类,我在编译时遇到错误,我无法理解.错误是:
symbol:variable aList
location:class java.lang.Object for(graphNode node:map.get(i).aList){
aList变量是一个TreeSet,存储在每个节点中,该节点包含相应图形中节点所连接的节点.我在上面的main方法中使用完全相同的语法,它不会给出任何错误.此外,当我在遍历方法中打印出地图中的所有节点时,它会打印整数键,而不是它应该具有的graphNode值.我现在很困惑.谢谢你的帮助.
import java.util.*;
import java.io.*;
public class HW1 {
public static void main (String[] args) throws Exception {
Scanner sc = new Scanner(new File(args[0]));
sc.useDelimiter("(\\s)"); // divide up by whitespcae
TreeMap<Integer, graphNode> map = new TreeMap<Integer, graphNode>();
int totalNodes = Integer.parseInt(sc.next());
int totalEdges = Integer.parseInt(sc.next());
// Fill up the map with nodes
for(int i = 1; i <= totalNodes ; i++) {
map.put(i, new graphNode(i, null, 10000));
}
// Add all the edges to the adjacency list
while(sc.hasNext()){
int start = Integer.parseInt(sc.next());
int end = Integer.parseInt(sc.next());
graphNode startNode = map.get(start);
graphNode endNode = map.get(end);
if(!startNode.aList.contains(endNode)){
startNode.aList.add(endNode);
}
if(!endNode.aList.contains(startNode)){
endNode.aList.add(startNode);
}
}
for(int i = 1; i <= map.size(); i++){
for(graphNode node: map.get(i).aList){
System.out.print(node.value+" ");
}
System.out.println("");
}
traverse(map);
}
public static void traverse(TreeMap map){
for(int i = 1; i <= map.size(); i++){
for(graphNode node: map.get(i).aList){
System.out.print(node.value+" ");
}
System.out.println("");
}
}
}
import java.util.*;
import java.io.*;
public class graphNode implements Comparable<graphNode> {
int value;
int distance;
graphNode prev;
TreeSet<graphNode> aList;
String color;
public graphNode(int value, graphNode prev, int distance) {
this.value = value;
this.prev = prev;
this.distance = distance;
aList = new TreeSet<graphNode>();
String color = "white";
}
public String toString() {
return value + "";
}
public int compareTo(graphNode other) {
if (this.value < other.value){
return -1;
}else if (this.value == other.value){
return 0;
}else{
return 1;
}
}
Run Code Online (Sandbox Code Playgroud)
}
在main,map是一个
TreeMap<Integer, graphNode> map = new TreeMap<Integer, graphNode>();
Run Code Online (Sandbox Code Playgroud)
但在traverse,它只是一个TreeMap.所以get(i)返回一个Object,而不是一个graphNode.
一个Object没有aList场.
宣布
public static void traverse(TreeMap<Integer, graphNode> map){
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
158 次 |
| 最近记录: |